Skip to content
AgileLogics
5 min read

Networking Basics: Sockets

Prerequisites: Inter-process communication: pipes

A socket is an endpoint for network communication — the same core API (socket, bind, listen, accept, connect) underlies HTTP servers, databases, and every other networked service, however high-level the language on top of it.

#include <sys/socket.h>
#include <netinet/in.h>

int main(void) {
    int serverFd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in address = {0};
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(8080);

    bind(serverFd, (struct sockaddr *) &address, sizeof(address));
    listen(serverFd, 5);

    int clientFd = accept(serverFd, NULL, NULL);
    char buffer[1024] = {0};
    read(clientFd, buffer, sizeof(buffer));
    printf("Received: %s\n", buffer);

    close(clientFd);
    close(serverFd);
    return 0;
}

htons converts a port number to network byte order — a reminder that raw sockets operate below any framework that would normally hide this detail.