Network programming
What is a socket:
a socket is a way to speak to other programs using standard Unix file descriptors. When Unix programs
do any sort of I/O operation, they do it by reading or writing to a file descriptor. A file descriptor is
simply an integer associated with an open file, and that file can be a network connection, a FIFO, a
pipe, a terminal and so on. To get a file descriptor for network communication, you make a call to the
socket() system routine, that returns the socket descriptor, and you communicate through it using the
specialized send() and recv() socket calls.
There are many type of sockets depending on which Unix flavour you are on, but the one I’ll be
studying is internet sockets.
Types of internet sockets:
There are multiple types of internet sockets, but the one I’ll be occupying with are “stream sockets” and
“datagram sockets”, or “SOCK_STREAM” and “SOCK_DGRAM” respectively.
Stream sockets are relaiable two-way connected communication streams, the message sent through it
will arrive for sure, and it will aslo be error-free. This type of sockets is obtained thanks to the use of a
specific protocol called “Transmission Control Protocol”, or TCP. Stream sockets are used in telnet,
ssh, http and so on.
Datagram sockets are also called “connectionless” because with them you don’t have to maintain an
open connection like with stream sockets. If you send something through this type of socket it is not
guaranteed that your packet will arrive, and if it arrives it may not be error-free.
Datagram sockets are used when a TCP stack is unavailable or when there’s no need of a parfect
accuracy of the information sent, like with multiplayer games, streaming audio, video calls, tftp and so
on.
Data encapsulation
When a packet is born, it is wrapped in an header (and sometimes also a footer) by the first protocol
(say the tftp) protocol, then the whole thing is encapsulated again by the next protocol (say, UDP), then
again by the next one (IP), and then again by the final one on the hardware layer (say, Ethernet).