Header Ads

HTTPS GET in C: Count Response Bytes with libcurl

How many bytes did the server actually send? This small C client sends an HTTPS GET to example.com and counts each body chunk as it arrives. The program needs only a counter, even for a response split across many reads.

GET in C with libcurl

Build and run

Use a C11 compiler, the libcurl development headers and library, and a working CA trust store. On a system with pkg-config, save the listing as https_get.c and run these commands.

cc -std=c11 -Wall -Wextra https_get.c -o https_get $(pkg-config --cflags --libs libcurl)
./https_get

Complete C program

#include <curl/curl.h>
#include <stdio.h>
#include <stdint.h>

static size_t count_bytes(char *data, size_t size, size_t count, void *ctx)
{
    size_t *total = ctx;
    (void)data;
    if (count && size > SIZE_MAX / count) return 0;
    size_t n = size * count;
    if (n > SIZE_MAX - *total) return 0;
    *total += n;
    return n;
}

int main(void)
{
    if (curl_global_init(CURL_GLOBAL_DEFAULT) != CURLE_OK) return 1;
    CURL *c = curl_easy_init();
    int result = 1;
    if (c) {
        long status = 0;
        size_t bytes = 0;
        CURLcode rc = curl_easy_setopt(c, CURLOPT_URL, "https://example.com/");
        if (!rc) rc = curl_easy_setopt(c, CURLOPT_TIMEOUT, 15L);
        if (!rc) rc = curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, count_bytes);
        if (!rc) rc = curl_easy_setopt(c, CURLOPT_WRITEDATA, &bytes);
        if (!rc) rc = curl_easy_perform(c);
        if (!rc) rc = curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &status);
        if (rc) fprintf(stderr, "Transfer: %s\n", curl_easy_strerror(rc));
        else {
            printf("HTTP %ld, %zu body bytes\n", status, bytes);
            result = (status < 200 || status >= 300);
        }
        curl_easy_cleanup(c);
    }
    curl_global_cleanup();
    return result;
}

Read the result

A response delivered in three chunks of 80, 100 and 20 bytes produces a count of 200. HTTP headers are excluded. Returning the full chunk length tells libcurl to continue. A short return stops the transfer. The callback receives raw bytes, so strlen would give the wrong answer for a body containing a zero byte.

The fixed URL uses HTTPS. libcurl checks the certificate and host name with its normal defaults. The 15-second timeout bounds the transfer. A transport error such as a failed certificate check is reported separately from an HTTP result such as 404. A redirect is reported with its 3xx status.

Reference: libcurl documentation for this example.

No comments