簡體   English   中英

Linux C您如何為http響應塊動態分配內存?

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

我是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?";
}

非常感謝您的幫助,謝謝!

您可以使用malloc來擺在首位,並分配塊realloc放大,如果它被證明不是足夠大。 然后,您只需將指針return到該塊即可(不要忘記在結尾處放置一個終止的零字節)。 完成后,調用者可以free該塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM