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

标签 c linux http memory dynamic

我是 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/

相关文章:

java - Java 的 REST 和 HTTP API 客户端,如 RestSharp(http ://restsharp. org/)

java - python和php中提交html表单很简单,新手用java可以吗?

python - 从 asyncio StreamReader 读取

linux - 如果还没有换行符,则在与模式匹配的行之前创建换行符

linux - 了解 Linux 内核循环缓冲区

c++ - 进程是否在退出时自动清理 pthreads 占用的资源

c - 使用递归查找最长的单词 C

linux - Gatttool : Limited to 5 connections?

c - 这段代码在 GCC 中意味着什么?

c - 我有旧的 C 程序,我可以在其中看到声明