libcurl
libcurl is a C library for URL transfers. It speaks HTTP(S), FTP, and a long list of other protocols so your program does not have to write sockets and TLS by hand.
Detailed Explanation
You link -lcurl and include <curl/curl.h>. Global setup is curl_global_init once per process and curl_global_cleanup at the end. Each transfer is a CURL * easy handle: curl_easy_init, curl_easy_setopt, curl_easy_perform, curl_easy_cleanup.
Options are the API. CURLOPT_URL is the URL. CURLOPT_WRITEFUNCTION plus CURLOPT_WRITEDATA receive the body in chunks. The default write function prints to stdout, which is why a forgotten callback dumps the response on your terminal. CURLOPT_ERRORBUFFER and the CURLcode return are the error channel. CURLOPT_FOLLOWLOCATION follows redirects; cap it. CURLOPT_TIMEOUT is not optional on a server.
HTTPS needs a CA bundle the library can see. A client that sets CURLOPT_SSL_VERIFYPEER to 0 has turned off the reason you used TLS. Do not.
The multi interface (CURLM *) runs many transfers on one thread with poll. The easy interface plus one thread per request is simpler and fine until the thread count hurts.
libcurl is a client. It does not serve HTTP. For a server you want a different library or a raw socket loop. libcurl can talk to your server in tests, which is a good way to avoid mocking HTTP by hand.
Thread safety: easy handles are not shared across threads. The global init must happen before any thread uses curl. Some DNS backends have their own rules; the docs' thread-safety page is the source.
Code Examples
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
struct Buf {
char *data;
size_t len;
};
static size_t on_write(char *ptr, size_t size, size_t nmemb, void *user)
{
size_t n = size * nmemb;
struct Buf *b = user;
char *p = realloc(b->data, b->len + n + 1);
if (p == NULL) {
return 0; /* signals error to curl */
}
b->data = p;
memcpy(b->data + b->len, ptr, n);
b->len += n;
b->data[b->len] = '\0';
return n;
}
int main(void)
{
CURL *c = curl_easy_init();
if (c == NULL) {
return 1;
}
struct Buf b = { 0 };
curl_easy_setopt(c, CURLOPT_URL, "https://example.com/");
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, on_write);
curl_easy_setopt(c, CURLOPT_WRITEDATA, &b);
curl_easy_setopt(c, CURLOPT_TIMEOUT, 10L);
CURLcode rc = curl_easy_perform(c);
if (rc == CURLE_OK && b.data != NULL) {
printf("%zu\n", b.len);
}
free(b.data);
curl_easy_cleanup(c);
return rc == CURLE_OK ? 0 : 1;
}Common Gotchas
Disabling peer verification (`SSL_VERIFYPEER 0`) accepts any certificate
that is not HTTPS anymore.
The default write callback prints to stdout
set your own or you will mix the body with logs.
Returning `0` from the write callback aborts the transfer
that is how you signal `realloc` failure.
Call `curl_global_init` once
calling it from two threads without coordination is undefined in older curl versions.