Sockets
A socket is a file-descriptor-like endpoint for network I/O. In C you create one with socket, connect or bind it, then send / recv (or read / write) bytes. The C standard does not define this API; POSIX and Winsock do.
Detailed Explanation
Web programming in C starts at the transport, not at a framework. socket(AF_INET, SOCK_STREAM, 0) asks for a TCP socket. connect on the client side, or bind / listen / accept on the server side, attaches it to an address. After that you have a bidirectional byte stream. HTTP, TLS, and your own protocol are bytes you send on that stream.
Addresses are struct sockaddr_in (IPv4) or sockaddr_in6 (IPv6). getaddrinfo turns a hostname and service name into a list of those structures and is the replacement for gethostbyname. It is reentrant. Check every return; DNS and routing fail.
send and recv may transfer fewer bytes than you asked. A send of 100 that returns 40 is not an error. You loop. A recv of 0 means the peer closed. A return of -1 with EINTR means a signal; retry. EAGAIN on a non-blocking socket means "not now."
Blocking sockets stall the thread. A single-threaded server that accepts and then reads a slow client handles one client. The next step is fork per client, a thread per client, or non-blocking I/O with poll / epoll / kqueue. Those are the C versions of an event loop.
Close with close (POSIX) or closesocket (Windows). shutdown half-closes. A socket is not a FILE * unless you fdopen it, and mixing stdio buffering with raw recv is a good way to lose bytes.
This page is conceptual plus POSIX. Windows uses WSAStartup and slightly different types. Portable code hides the differences behind a handful of wrappers.
Code Examples
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
int main(void)
{
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo("example.com", "80", &hints, &res) != 0) {
return 1;
}
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if (fd < 0) {
freeaddrinfo(res);
return 1;
}
if (connect(fd, res->ai_addr, res->ai_addrlen) != 0) {
close(fd);
freeaddrinfo(res);
return 1;
}
const char *req = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n";
send(fd, req, strlen(req), 0);
char buf[64];
ssize_t n = recv(fd, buf, sizeof buf - 1, 0);
if (n > 0) {
buf[n] = '\0';
fputs(buf, stdout);
}
close(fd);
freeaddrinfo(res);
return 0;
}Common Gotchas
Treating a short `send`/`recv` as a full transfer drops or duplicates protocol data
loop until the count is done or the peer closes.
`gethostbyname` is obsolete and not thread-safe
use `getaddrinfo`.
A socket is not encrypted
TLS is a library on top of the same file descriptor.
Forgetting `freeaddrinfo` leaks the resolver's list
Forgetting `freeaddrinfo` leaks the resolver's list