II.3.4.2-Sockets

The socket is the basis for 4.3BSD Unix network I/O. It is an endpoint for communication. The designers of the socket tried to have it behave just like the Unix files and devices (whenever it made sense).
Sockets are created, maintained, used and destroyed using a set of special system calls.

A socket is first created (socket system call). It is associated to a protocol (TCP or UDP for the TCP/IP protocol suite) at birth. The user receives a socket descriptor, a small integer which will be the identification number for all further access to the socket.

The bind system call is used to associate a local protocol port number to the socket. The socket can now receive data. If it is to be used with stream service, it must also be bound to a destination address. This is done through the connect system call.
The connect system call can be applied to a socket using a packet delivery service, but then it simply provides automatic addressing for outgoing packets. When used with a stream service, it also takes care of all the details associated with the opening of a virtual connection.

Data can now be sent using the socket. This is done using write, writev, send (connected socket only), sendto, sendmsg.
To receive data, read, readv, recv (connected socket only), recvfrom, or rcvmsg should be called.

The listen system call is used to assign a queue length to a connected socket.
The accept system call tells a TCP socket to wait for a connection. It is blocking, and returns a new socket descriptor when accepting the connection.
The select system call allows a single process to wait for a connection on multiple sockets.

The socket interface also provides a number of library functions to handle data transmission, and to get addresses, protocol numbers and names, as well as information about networks and hosts. The details of all these functions can be found in [11].

This chapter exposed the basic workings of the Internet and its protocols. These will only be accessed through the socket interface, but knowing how a network switches packets around, maintains routing information and basic data about its hosts, and handles error conditions will prove important to the conception of the virtual network Tierra presents to its creatures.