我是C的新手,我试图将BUFSIZE的http响应块“附加”到字符串total_response然后返回它我将如何这样做?
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?";
}
非常感谢任何帮助,谢谢!
答案 0 :(得分:1)
您可以使用malloc
首先分配块,realloc
如果结果不够大则使用return
来扩大它。然后你可以free
指向块的指针(不要忘记在末尾放置一个终止的零字节)。调用者完成后可以{{1}}阻止它。