HTTP
HTTP is a request/response protocol that usually rides on a TCP socket (or on TLS). In C you either write the text yourself or you let a library such as libcurl write it. There is no HTTP type in the language.
Detailed Explanation
A request is bytes:
GET /path HTTP/1.1\r\n
Host: example.com\r\n
Connection: close\r\n
\r\n
The line endings are \r\n. The headers end with a blank line. A body, if any, follows and is sized by Content-Length or by chunked transfer encoding. A response starts with HTTP/1.1 200 OK\r\n and the same header rules.
C will not parse this for you. You send the request. You recv into a buffer. You find the \r\n\r\n that ends the headers. You parse Content-Length with strtol and read that many more bytes, looping on short reads. Chunked encoding is a small state machine. An incomplete parse is how security bugs start: a header larger than your buffer, a negative length after wrap, a request line without a method.
HTTP/1.0 with Connection: close is the simplest client: one request, read until recv returns 0. HTTP/1.1 keep-alive reuses the socket and requires correct lengths. HTTP/2 is binary and is not something you should parse by hand.
Status codes are integers with conventions: 2xx success, 3xx redirect, 4xx client error, 5xx server error. The body is still bytes. JSON, HTML, and files are all bodies. C has no built-in JSON; you pick a parser.
For anything beyond a learning client, use libcurl or a dedicated server library. The protocol looks small and has decades of sharp edges (request smuggling, header injection, Host handling). Hand-rolled HTTP is a teaching tool and a liability in production.
Code Examples
#include <stdio.h>
#include <string.h>
static void build_get(char *out, size_t out_sz, const char *host, const char *path)
{
snprintf(out, out_sz,
"GET %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n\r\n",
path, host);
}
int main(void)
{
char req[128];
build_get(req, sizeof req, "example.com", "/");
fputs(req, stdout);
/* prints a legal HTTP/1.0 GET */
return 0;
}#include <stdio.h>
#include <string.h>
static int header_end(const char *buf, size_t n)
{
return n >= 4 && memmem(buf, n, "\r\n\r\n", 4) != NULL;
}
int main(void)
{
const char *p = "HTTP/1.0 200 OK\r\nContent-Length: 0\r\n\r\n";
printf("%d\n", header_end(p, strlen(p))); /* prints: 1 */
return 0;
}Common Gotchas
Building a request with `sprintf` and a user-supplied path enables header injection if the path contains `\r\n`
reject or encode CR/LF.
`Content-Length` is a decimal string, not a trusted `int`
overflow it and you read past the body into the next request (smuggling).
`\n` alone is tolerated by some servers and is not what you should send
write `\r\n`.
A teaching `recv` loop that stops at the first packet has only part of the respo
A teaching `recv` loop that stops at the first packet has only part of the response