gpt4 book ai didi

c - Linux C 如何为 http 响应 block 动态分配内存?

转载 作者:太空宇宙 更新时间:2023-11-04 10:32:16 24 4
gpt4 key购买 nike

我是 C 的新手,我正在尝试将 BUFSIZE 的 http 响应 block “附加”到字符串 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?";
}

非常感谢任何帮助,谢谢!

最佳答案

您可以首先使用malloc 分配 block ,如果发现 block 不够大,可以使用realloc 来扩大它。然后您可以返回 指向该 block 的指针(不要忘记在末尾放置一个终止零字节)。调用方可以在 block 用完后释放 block 。

关于c - Linux C 如何为 http 响应 block 动态分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com