semanji semanji - 3 months ago 7
C Question

Linux C how do you dynamically allocate memory for http response chunks?

Im new to C and im trying to "append" http response chunks of BUFSIZE into string total_response then return it how would i go about doing so?

char *
http_request(char * postdata, char * method, char * host, char * page,
int port, char * useragent)
{
struct sockaddr_in * remote;
int sock;
int tmpres;
char * ip, * get;

sock = create_tcp_socket();
ip = get_ip(host);
remote = (struct sockaddr_in * ) malloc(sizeof(struct sockaddr_in * ));
remote -> sin_family = AF_INET;
tmpres = inet_pton(AF_INET, ip, (void *)(&(remote -> sin_addr.s_addr)));
if (tmpres < 0)
{
//error
return 0;
}
else if (tmpres == 0)
{
//error
return 0;
}
remote -> sin_port = htons(port);

if (connect(sock, (struct sockaddr * ) remote, sizeof(struct sockaddr)) < 0)
{
//error
return 0;
}
get = build_get_query(postdata, method, HOST, PAGE, USERAGENT);
//fprintf(stderr, "%s", get); //response

// Send the query to the server
int sent = 0;
while (sent < strlen(get))
{
tmpres = send(sock, get + sent, strlen(get) - sent, 0);
if (tmpres == -1)
{
//error
return 0;
}
sent += tmpres;
}
// now it is time to receive the page
char buf[BUFSIZ + 1];
memset(buf, 0, sizeof(buf));
int bytes;
do
{
memset(buf, 0, sizeof(buf));
bytes = recv(sock, buf, 1024, 0);
printf("%s", buf); //handle response chunks
if (bytes < 0)
perror("ERROR reading response from socket");
if (bytes == 0)
break;
}
while (1);
free(get);
free(remote);
free(ip);
close(sock);
return "CANT RETURN LOCAL VARIABLE BUF?";
}


Very much appreciate any help, thanks!

Answer

You can use malloc to allocate the block in the first place and realloc to enlarge it if it turns out not to be large enough. You can then just return the pointer to the block (don't forget to put a terminating zero byte on the end). The caller can free the block when it's done with it.