9) Socket and Network Programming

A technical guide to network programming, the lifecycle of sockets, and client-server communication.

Introduction to Network Programming

Writing code that can communicate through a network of computers requires the use of standard interfaces defined as Sockets.

What is a Socket

A socket represents a logical bidirectional communication endpoint, uniquely identified by the combination of an IP address and a TCP/UDP port.

There are two main families of sockets based on the underlying transport layer protocols.

Stream Sockets rely on the TCP protocol to ensure reliable, ordered, and error-free transmission.

Datagram Sockets use UDP to transmit individual data blocks at the maximum possible speed, without guarantees of delivery.

Lifecycle of a TCP Server

To establish correct communication, the server must follow a precise sequence of system calls.

The socket() call initializes the interface and sets the address family and protocol type.

The bind() call associates the created socket with a local IP address and a specific port number on the machine.

The listen() call puts the server in passive listening mode, ready to receive connection attempts from clients.

The accept() call is blocking: it extracts the first connection request in the queue and creates a new socket dedicated to the channel.

Through read() and write() (or recv() and send()), the server exchanges messages with the client before closing the connection with close().

The Lifecycle of a TCP Client

The client follows a much simpler path, avoiding the bind and listen phases.

After calling socket(), it invokes connect() to actively request the opening of the TCP Three-Way Handshake with the server.

Once the connection is accepted, it can start transmitting and processing data until the resources are released.

Conclusions

Mastering socket programming is essential to understand how modern web servers and microservices are implemented.

🔗 Resources and References

Wikipedia - Socket di rete Python - Socket Programming Tutorial GeeksforGeeks - Socket Programming in C/C++ Oracle - What is a Socket?