I’m trying to store some binary data obtained from read() in my buffer using the memcpy() function.
Basically, I want to store buf in my buffer:
#define MAX_BUFFER_SIZE 256
//...
char *
httpget(const char * domain, const int port, const char * headers)
{
int sockfd;
int buf_size = MAX_BUFFER_SIZE;
struct sockaddr_in sock_addr;
struct hostent * host;
char * buffer;
char * newbuf;
char * tbuf;
sockfd = socket(AF_INET,SOCK_STREAM,0);
if( sockfd == -1 )
{
return NULL;
}
host = gethostbyname(domain);
if( NULL == host )
{
close(sockfd);
return NULL;
}
memset(&sock_addr, '\0', sizeof(sock_addr));
sock_addr.sin_family = AF_INET;
memcpy( &sock_addr.sin_addr.s_addr,
host -> h_addr,
host -> h_length );
sock_addr.sin_port = htons(port);
if( connect(sockfd, (struct sockaddr *) &sock_addr, sizeof(sock_addr)) == -1)
{
close(sockfd);
return NULL;
}
if( write(sockfd, headers, strlen(headers) + 1) == -1)
{
close(sockfd);
return NULL;
}
buffer = malloc( MAX_BUFFER_SIZE );
tbuf = malloc( MAX_BUFFER_SIZE );
if(buffer == NULL || tbuf == NULL)
{
return NULL;
}
int bytesloaded = 0;
int readed;
while( (readed = read(sockfd, tbuf, MAX_BUFFER_SIZE)) > 0 )
{
if(bytesloaded + readed >= buf_size)
{
buf_size = buf_size + MAX_BUFFER_SIZE;
newbuf = realloc(buffer, buf_size);
if(newbuf != NULL)
{
buffer = newbuf;
}
else
{
return NULL;
}
}
memcpy(buffer, tbuf, readed);
bytesloaded += readed;
}
close(sockfd);
printf("buffer = %s", buffer);
return buffer;
}
but when I printf(“%s”,buffer); I get only the HTTP Headers and �PNG characteres from binary that have 7007 content-length. how to fix this? I hope this is clear for you. any help is very appreciated.Thanks in advance.
I think you want:
You aren’t seeing the entire response when you try to dump it using
printf("%s",buffer)because the.pngimage being sent in the response is binary data that’s likely to contain a null'\0'byte, and theprintf()will stop at that point.You have all sorts of other options to examine the data returned in the response (or information about it): look at
bufferin the debugger, dump thebytesloadedvariable, dumpbufferusing a function that will convert it to hex for display, and/or write the response body (after the headers and the CR/LF that follows the headers) to a.pngfile and take a look at it in something that will display an image.