-1

I have the following string:

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 11:53:22 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

��(�ͱ���I�O����H�����ч��
                          �4�@��AQ������t

I want to extract up to the "\r\n\r\n", discarding the binary data. I.e. :

HTTP/1.1 200 OK
Date: Tue, 06 Dec 2011 11:53:22 GMT
Server: Apache/2.2.14 (Ubuntu)
X-Powered-By: PHP/5.3.2-1ubuntu4.9
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 48
Content-Type: text/html

How to do this in C?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Eamorr
  • 9,872
  • 34
  • 125
  • 209

2 Answers2

6

This could easily be done by simple finding the first two sequential linebreaks, since this terminates the header, and then copy everything upto that point to a separate buffer:

// Find the end of the header, which is terminated
// by two line breaks
char* end = strstr(header, "\r\n\r\n");
char* buffer = 0;
if (end) {
    // Allocate memory to hold the entire header
    buffer = malloc((end - header) + 1);
    if (buffer) {
        // Copy header to buffer
        memcpy(buffer, header, end - header);
        // NULL terminate the buffer
        buffer[end - header] = 0;
        // Do something with the buffer here
    
        // Don't forget to release the allocated memory
        free(buffer);
    }
}
Cyclonecode
  • 29,115
  • 11
  • 72
  • 93
1

You could use the strstr function.

But be aware that there exist good C libraries for HTTP client (like libcurl) and for HTTP server (like onion) sides. And that HTTP is complex in its details.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I tried strstr, but it returns a pointer to the binary data! `strstr(buf,"\r\n\r\n")` - how to overcome this? – Eamorr Dec 06 '11 at 12:48
  • Of course it does, you'll need to manipulate everything UP TO the pointer returned by strstr (see @Krister Andersson post below) – KevinDTimm Dec 06 '11 at 12:53