Header Ads

HTTPS HEAD in C: Read the Status and Content Type with libcurl

A download manager can ask what a resource looks like before fetching its contents. Send an HTTPS HEAD request and inspect the status code and media type. The server sends response headers and omits the body.

HEAD 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_head.c and run these commands.

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

Complete C program

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

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;
        char *type = NULL;
        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_NOBODY, 1L);
        if (!rc) rc = curl_easy_perform(c);
        if (!rc) rc = curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &status);
        if (!rc) rc = curl_easy_getinfo(c, CURLINFO_CONTENT_TYPE, &type);
        if (rc) fprintf(stderr, "Transfer: %s\n", curl_easy_strerror(rc));
        else {
            printf("HTTP %ld, type %s\n", status, type ? type : "(unspecified)");
            result = (status < 200 || status >= 300);
        }
        curl_easy_cleanup(c);
    }
    curl_global_cleanup();
    return result;
}

Read the result

For an HTML page the output may look like HTTP 200, type text/html. A server may add a charset, omit Content-Type, or reject HEAD with 405. The type pointer belongs to libcurl, so the program prints it before cleaning up the handle. A successful HEAD does not tell you the body contents.

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