Skip to content
Tutorials Center
My learning

Topics

Lesson 94 of 135 ยท Advanced C

Network Programming with Sockets

Learn socket programming in C - build a TCP client and server with socket, bind, listen, accept and connect, handle byte order and getaddrinfo, and use UDP.

Every web browser, database driver and chat app talks over the network through sockets. A socket is an endpoint for communication: your program asks the operating system for one, connects it to an address, and then sends and receives bytes through it much like a file. The API you'll learn here is the Berkeley sockets (POSIX) interface from <sys/socket.h>. It dates from the 1980s, and it still sits underneath almost every networking library in every language.

You'll build a TCP server and client, learn why port numbers need htons, look up addresses with getaddrinfo, deal with the fact that TCP has no message boundaries, and finish with UDP. Our sandbox has no internet access, but the loopback address 127.0.0.1 works, so each example runs a server and a client inside one program: the server in a thread and the client in main. The code is exactly what you'd split into two programs on two machines.

You should know pointers, structures and the basics of threads, and it helps to have read Low-Level I/O with System Calls, because a socket is a file descriptor.

TCP and UDP

Two transport protocols cover nearly everything:

TCP (SOCK_STREAM) UDP (SOCK_DGRAM)
Connection Yes: connect first, then talk No: each packet is addressed separately
Delivery Reliable, in order, no duplicates May be lost, duplicated or reordered
Data shape A continuous byte stream Separate datagrams (messages)
Typical uses HTTP, databases, SSH, email DNS, games, video calls, metrics

An address on the network is an IP address plus a port, a 16-bit number that identifies a program on that machine (a web server usually listens on port 80 or 443). Ports below 1024 need administrator rights on most systems.

Addresses and byte order

Different CPUs store multi-byte integers in different orders. x86 and most ARM chips are little-endian (least significant byte first), but network protocols use big-endian, called network byte order. Four functions convert between the two: htons and htonl ("host to network short/long") for 16-bit ports and 32-bit IPv4 addresses, and ntohs/ntohl for the way back. On a big-endian machine they do nothing, so calling them is always correct.

IPv4 addresses live in a struct sockaddr_in, and inet_pton/inet_ntop convert between text like "192.168.1.20" and the binary form:

C Ports, byte order and IPv4 addresses

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The bytes 1F 90 are the big-endian form of 8080; on this little-endian server, the raw uint16_t 8080 would be stored as 90 1F. inet_pton returns 1 on success and 0 for text that isn't a valid address. Forgetting htons on a port is a classic bug: the program binds to port 36895 (0x901F) instead of 8080, and nothing tells you.

Every socket function takes a pointer to the generic struct sockaddr, so you cast your sockaddr_in (or sockaddr_in6 for IPv6) and pass its size. The sin_family field tells the system which kind it really is.

Finding addresses with getaddrinfo

Hard-coding IPv4 addresses is fine for a demo, but real programs start from a host name and a service such as "example.com" and "443". getaddrinfo resolves them into a linked list of ready-to-use addresses, covering IPv4 and IPv6, so the same code works with both. You try each address in turn until one connects, then free the list with freeaddrinfo. Errors come back as a return code that gai_strerror turns into text (not through errno):

C Resolving names with getaddrinfo

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

localhost resolves to both ::1 (IPv6) and 127.0.0.1 (IPv4). A numeric address is returned as is. example.com fails here because the sandbox has no network; on your own machine it prints the site's real addresses. A server passes NULL as the host with hints.ai_flags = AI_PASSIVE to get "any address" suitable for bind.

A TCP server and client

A TCP server and a TCP client make different calls in a fixed order:

TEXT
Server                                   Client
socket()    create the socket            socket()
bind()      attach it to address:port
listen()    start accepting connections
accept()    wait for a client  <-------  connect()
recv()/send()  talk on the new socket    send()/recv()
close()                                  close()

The important twist is that accept returns a new socket for each client. The listening socket keeps waiting for further connections, while the new one carries the conversation with that client. Here the server reads one line, sends it back in uppercase, and closes the connection. The server binds to port 0, which lets the system pick a free port; getsockname reveals which one, and the client connects to it:

C A TCP echo server and client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The client gets HELLO, SOCKETS back. The last recv returns 0, which is how TCP reports that the other side closed the connection; -1 means an error. The order works out because listen is called before the client connects: the system queues incoming connections (up to the listen backlog) even before the server thread reaches accept.

On a real server you would also set the SO_REUSEADDR option before bind, so a restarted server can reuse its port immediately instead of failing with "Address already in use" for a minute or two:

C
int yes = 1;
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes);

TCP is a stream, not a list of messages

This is the most common misunderstanding in network code. TCP delivers bytes in order, but it doesn't preserve the boundaries between your send calls. Three sends can arrive in one recv, and one send can arrive split across several. Two consequences follow:

  • send may write fewer bytes than you asked for, so loop until everything is sent.
  • recv returns whatever has arrived. Your protocol must mark where each message ends, either with a delimiter (such as a newline) or with a length prefix before each message.

The next server reads into a buffer and only processes complete lines, keeping any partial line for the next recv. The client sends three messages in two sends, one of them split mid-line, and the server still sees exactly three commands:

C Reading newline-framed messages from a stream

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

However the bytes are split, the output is the same three commands: LIST, GET 42 and PUT 7 blue. Real protocols work the same way: HTTP/1.1 headers end with a blank line and the body length comes from a Content-Length header, while many binary protocols send a 4-byte length (in network byte order) before each message.

Serving more than one client

The servers above handle one client and stop. A real server loops on accept, and must not let one slow client block the others. There are three standard designs:

  • A thread per client: accept, then pthread_create with the new socket. Simple, and fine for dozens or hundreds of clients.
  • A thread pool: a fixed number of worker threads take accepted sockets from a queue (the producer-consumer pattern from Multithreading).
  • An event loop: one thread watches many sockets with poll (portable) or epoll (Linux) / kqueue (BSD, macOS) and only reads from sockets that have data. This is how nginx, Redis and Node.js handle tens of thousands of connections.

Two more details matter for any server. Writing to a connection the client has closed raises SIGPIPE, which kills the process by default; call signal(SIGPIPE, SIG_IGN) at startup (or pass MSG_NOSIGNAL to send on Linux), and handle the EPIPE error instead. See Signals and Signal Handling. And to avoid waiting forever on a silent peer, set a receive timeout with the SO_RCVTIMEO socket option, or use poll with a timeout.

UDP: datagrams without a connection

UDP has no listen, accept or connect step. A UDP socket is bound to a port and then exchanges individual datagrams with sendto (which takes the destination address) and recvfrom (which reports the sender's address). Each recvfrom returns exactly one datagram, so message boundaries are preserved, but a datagram can be lost and nobody will tell you. Because nothing waits for a connection, this demo doesn't even need a thread:

C Sending datagrams with UDP

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Three sendto calls produce three separate datagrams, each received whole. On loopback nothing gets lost, but across a real network an application using UDP must tolerate missing or reordered packets, for example by numbering them or simply accepting that an old reading was dropped.

Errors and portability

Every socket call can fail, and network failures are normal events, not exotic ones: a host is unreachable, a connection is refused or reset, a peer disappears. Check every return value. Most calls return -1 and set errno (use perror or strerror, see Error Handling); getaddrinfo returns its own codes for gai_strerror. A call interrupted by a signal fails with EINTR and can simply be retried.

On Windows the API is nearly the same but comes from Winsock: include <winsock2.h> and <ws2tcpip.h>, call WSAStartup once before any socket call, close sockets with closesocket instead of close, and read errors with WSAGetLastError. Libraries such as libcurl (for HTTP) or libuv (for event loops) hide these differences, and for encrypted connections you'll need a TLS library such as OpenSSL on top of the plain socket.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a server call htons(8080) when filling sin_port?

    Without htons, a little-endian machine would store 8080 as bytes 90 1F, which the network reads as port 36895.
  2. 2. What does accept() return?

    The listening socket keeps accepting other clients; each accepted connection gets its own descriptor.
  3. 3. A client calls send() three times with "A\n", "B\n" and "C\n" over TCP. How many recv() calls does the server need?

    TCP is a byte stream without message boundaries. The server must split messages itself, here at each newline.
  4. 4. recv() on a TCP socket returns 0. What does it mean?

    0 means end of stream (orderly shutdown by the peer); -1 means an error.
  5. 5. Which statement about UDP is true?

    UDP keeps message boundaries and has no connection, but it gives no delivery or ordering guarantees.

Summary

  • A socket is a file descriptor for network communication: socket() creates it; TCP uses SOCK_STREAM, UDP uses SOCK_DGRAM.
  • Server: socket, bind, listen, then accept for each client (a new socket per connection). Client: socket, connect, then send/recv. close both ends.
  • Ports and IPv4 addresses go into struct sockaddr_in in network byte order: use htons/htonl and ntohs/ntohl, and inet_pton/inet_ntop for text.
  • getaddrinfo turns host names and services into IPv4/IPv6 addresses; report its errors with gai_strerror, and free the list.
  • TCP is a byte stream: loop on send, frame messages with delimiters or length prefixes, and treat recv returning 0 as "connection closed".
  • Servers handle many clients with threads, thread pools or poll/epoll; ignore SIGPIPE, set SO_REUSEADDR, and use timeouts.
  • UDP sends separate datagrams with sendto/recvfrom: no connection, no delivery guarantee. Windows uses the same API through Winsock.

Next: Undefined Behavior