Berkeley sockets


Berkeley sockets is an application programming interface for Internet sockets and Unix domain sockets, used for inter-process communication. It is commonly implemented as a library of linkable modules. It originated with the 4.2BSD Unix operating system, released in 1983.
A socket is an abstract representation for the local endpoint of a network communication path. The Berkeley sockets API represents it as a file descriptor in the Unix philosophy that provides a common interface for input and output to streams of data.
Berkeley sockets evolved with little modification from a de facto standard into a component of the POSIX specification. The term POSIX sockets is essentially synonymous with Berkeley sockets, but they are also known as BSD sockets, acknowledging the first implementation in the Berkeley Software Distribution.

History and implementations

Berkeley sockets originated with the 4.2BSD Unix operating system, released in 1983, as a programming interface. Not until 1989, however, could the University of California, Berkeley release versions of the operating system and networking library free from the licensing constraints of AT&T Corporation's proprietary Unix.
All modern operating systems implement a version of the Berkeley socket interface. It became the standard interface for applications running in the Internet. Even the Winsock implementation for MS Windows, created by unaffiliated developers, closely follows the standard.
The BSD sockets API is written in the C programming language. Most other programming languages provide similar interfaces, typically written as a wrapper library based on the C API.

BSD and POSIX sockets

As the Berkeley socket API evolved and ultimately yielded the POSIX socket API, certain functions were deprecated or removed and replaced by others. The POSIX API is also designed to be reentrant.
ActionBSDPOSIX
Conversion from text address to packed addressinet_atoninet_pton
Conversion from packed address to text addressinet_ntoainet_ntop
Forward lookup for host name/servicegethostbyname, gethostbyaddr, getservbyname, getservbyportgetaddrinfo
Reverse lookup for host name/servicegethostbyaddr, getservbyportgetnameinfo

Alternatives

The STREAMS-based Transport Layer Interface API offers an alternative to the socket API. Many systems that provide the TLI API also provide the Berkeley socket API.
Non-Unix systems often expose the Berkeley socket API with a translation layer to a native networking API. Plan 9 and Genode use file-system APIs with control files rather than file-descriptors.

Header files

The Berkeley socket interface is defined in several header files. The names and content of these files differ slightly between implementations. In general, they include:
FileDescription
sys/socket.hCore socket functions and data structures.
netinet/in.hAF_INET and AF_INET6 address families and their corresponding protocol families, PF_INET and PF_INET6. These include standard IP addresses and TCP and UDP port numbers.
sys/un.hPF_UNIX and PF_LOCAL address family. Used for local communication between programs running on the same computer.
arpa/inet.hFunctions for manipulating numeric IP addresses.
netdb.hFunctions for translating protocol names and host names into numeric addresses. Searches local data as well as name services.

Socket API functions

The Berkeley socket API typically provides the following functions:
The function socket creates an endpoint for communication and returns a file descriptor for the socket. It uses three arguments:
The function returns if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor.

bind

bind associates a socket with an address. When a socket is created with socket, it is only given a protocol family, but not assigned an address. This association must be performed before the socket can accept connections from other hosts. The function has three arguments:
Bind returns 0 on success and -1 if an error occurs.

listen

After a socket has been associated with an address, prepares it for incoming connections. However, this is only necessary for the stream-oriented data modes, i.e., for socket types. listen requires two arguments:
Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is returned.

accept

When an application is listening for stream-oriented connections from other hosts, it is notified of such events and must initialize the connection using function accept. It creates a new socket for each connection and removes the connection from the listening queue. The function has the following arguments:
accept returns the new socket descriptor for the accepted connection, or the value -1 if an error occurs. All further communication with the remote host now occurs via this new socket.
Datagram sockets do not require processing by accept since the receiver may immediately respond to the request using the listening socket.

connect

connect establishes a direct communication link to a specific remote host identified by its address via a socket, identified by its file descriptor.
When using a connection-oriented protocol, this establishes a connection. Certain types of protocols are connectionless, most notably the User Datagram Protocol. When used with connectionless protocols, connect defines the remote address for sending and receiving data, allowing the use of functions such as send and recv. In these cases, the connect function prevents reception of datagrams from other sources.
connect returns an integer representing the error code: 0 represents success, while –1 represents an error. Historically, in BSD-derived systems, the state of a socket descriptor is undefined if the call to connect fails, thus, portable applications should close the socket descriptor immediately and obtain a new descriptor with socket, in the case the call to connect fails.

gethostbyname and gethostbyaddr

The functions gethostbyname and gethostbyaddr are used to resolve host names and addresses in the domain name system or the local host's other resolver mechanisms. They return a pointer to an object of type struct hostent, which describes an Internet Protocol host. The functions use the following arguments:
The functions return a NULL pointer in case of error, in which case the external integer may be checked to see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid struct hostent * is returned.
These functions are not strictly a component of the BSD socket API, but are often used in conjunction with the API functions. Furthermore, these functions are now considered legacy interfaces for querying the domain name system. New functions that are completely protocol-agnostic have been defined. These new function are getaddrinfo and getnameinfo, and are based on a new addrinfo data structure.

Protocol and address families

The Berkeley socket API is a general interface for networking and interprocess communication, and supports the use of various network protocols and address architectures.
The following lists a sampling of protocol families defined in a modern Linux or BSD implementation:
IdentifierFunction or use
PF_LOCAL, PF_UNIX, PF_FILELocal to host
PF_INETInternet Protocol version 4
PF_AX25Amateur Radio AX.25
PF_IPXNovell's Internetwork Packet Exchange
PF_APPLETALKAppleTalk
PF_NETROMAmateur radio NetROM
PF_BRIDGEMultiprotocol bridge
PF_ATMPVCAsynchronous Transfer Mode Permanent Virtual Circuits
PF_ATMSVCAsynchronous Transfer Mode Switched Virtual Circuits
PF_INET6Internet Protocol version 6
PF_DECnetReserved for DECnet project
PF_NETBEUIReserved for 802.2LLC project
PF_SECURITYSecurity callback pseudo AF
PF_KEYPF_KEY key management API
PF_NETLINK, PF_ROUTErouting API
PF_PACKETPacket capture sockets
PF_ECONETAcorn Econet
PF_SNALinux Systems Network Architecture Project
PF_IRDAIrDA sockets
PF_PPPOXPPP over X sockets
PF_WANPIPESangoma Wanpipe API sockets
PF_BLUETOOTHBluetooth sockets

A socket for communications is created with the function, by specifying the desired protocol family as an argument.
The original design concept of the socket interface distinguished between protocol types and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix instead of. The -identifiers are intended for all data structures that specifically deal with the address type and not the protocol family.
However, this concept of separation of protocol and address type has not found implementation support and the -constants were defined by the corresponding protocol identifier, leaving the distinction between and constants as a technical argument of no practical consequence. Indeed, much confusion exists in the proper usage of both forms.
The POSIX.1—2008 specification doesn't specify any -constants, but only -constants

Raw sockets

s provide a simple interface that bypasses the processing by the host's TCP/IP stack. They permit implementation of networking protocols in user space and aid in debugging of the protocol stack. Raw sockets are used by some services, such as ICMP, that operate at the Internet Layer of the TCP/IP model.

Options for sockets

After creating a socket, it is possible to set options on it. Some of the more common options are:
Berkeley sockets can operate in one of two modes: blocking or non-blocking.
A blocking socket does not return control until it has sent some or all data specified for the operation. It is normal for a blocking socket not to send all data. The application must check the return value to determine how many bytes have been sent or received and it must resend any data not already processed. When using blocking sockets, special consideration should be given to accept as it may still block after indicating readability if a client disconnects during the connection phase.
On the other hand, a non-blocking socket returns whatever is in the receive buffer and immediately continues. If not written correctly, programs using non-blocking sockets are particularly susceptible to race conditions due to variances in network link speed.
A socket is typically set to blocking or nonblocking mode using the or functions.

Terminating sockets

The operating system does not release the resources allocated to a socket until the socket is closed. This is especially important if the connect call fails and will be retried.
When an application closes a socket, only the interface to the socket is destroyed. It is the kernel's responsibility to destroy the socket internally. Sometimes, a socket may enter a state, on the server side, for up to 4 minutes.
On SVR4 systems use of may discard data. The use of or SO_LINGER may be required on these systems to guarantee delivery of all data.

Client-server example using TCP

The Transmission Control Protocol is a connection-oriented protocol that provides a variety of error correction and performance features for transmission of byte streams. A process creates a TCP socket by calling the function with the parameters for the protocol family, the socket mode for Stream Sockets, and the IP protocol identifier for TCP.

Server

Establishing a TCP server involves the following basic steps:
The following program creates a TCP server listening on port number 1100:

#include
#include
#include
#include
#include
#include
#include
#include

int main

Client

Programming a TCP client application involves the following steps:

#include
#include
#include
#include
#include
#include
#include
#include

int main

Client-server example using UDP

The User Datagram Protocol is a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. Because of this minimal design, UDP has considerably less overhead than TCP. Being connectionless means that there is no concept of a stream or permanent connection between two hosts. Such data are referred to as datagrams.
UDP address space, the space of UDP port numbers, is completely disjoint from that of TCP ports.

Server

An application may set up a UDP server on port number 7654 as follows. The programs contains an infinite loop that receives UDP datagrams with function recvfrom.

  1. include
  2. include
  3. include
  4. include
  5. include
  6. include
  7. include /* for close for socket */
  8. include
int main

Client

The following is a client program for sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 at port number 7654.

  1. include
  2. include
  3. include
  4. include
  5. include
  6. include
  7. include
  8. include
  9. include
int main

In this code, buffer is a pointer to the data to be sent, and buffer_length specifies the size of the data.