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?
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);
}
}