TCP/UDP Sockets - Linux
A network socket is an endpoint of an inter-process communication across a computer network. Today, most communication between computers is based on the Internet Protocol, therefore most network sockets are Internet sockets. A socket address is the combination of an IP address and a port number. Based on this address, internet sockets deliver incoming data packets to the appropriate application process or thread.
If you want generic sockets written in Python, Perl, C and Java click here.
UDP
UDP is a simple transport-layer protocol. The application writes a message to a UDP socket, which is then encapsulated in a UDP datagram, which is further encapsulated in an IP datagram, which is sent to the destination. There is no guarantee that a UDP will reach the destination, that the order of the datagrams will be preserved across the network or that datagrams arrive only once.
UDP Socket API
As shown in the Figure 1, the steps of establishing a UDP socket communication on the client side are as follows:
- Create a socket using the socket() function;
- Send and receive data by means of the recvfrom() and sendto() functions.
Figure 1: UDP client-server.
TCP
TCP provides a connection oriented service, since it is based on connections between clients and servers. TCP provides reliability. When a TCP client send data to the server, it requires an acknowledgement in return. If an acknowledgement is not received, TCP automatically retransmit the data and waits for a longer period of time.
TCP Socket API
The sequence of function calls for the client and a server participating in a TCP connection is presented in Figure 2.
Figure 2: TCP client-server.
As shown in the figure, the steps for establishing a TCP socket on the client side are the following:
- Create a socket using the socket() function;
- Connect the socket to the address of the server using the connect() function;
- Send and receive data by means of the read() and write() functions.
- Close the connection by means of the close() function.
The steps involved in establishing a TCP socket on the server side are as follows:
- Create a socket with the socket() function;
- Bind the socket to an address using the bind() function;
- Listen for connections with the listen() function;
- Accept a connection with the accept() function. This call typically blocks until a client connects with the server.
- Send and receive data by means of write() and read().
- Close the connection by means of the close() function.