Berkeley sockets

Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain sockets, used for inter-process communication (IPC). It is commonly implemented as a library of linkable modules. It originated with the 4.2BSD Unix released in 1983.

The API represents a socket – an abstract representation (handle) for the local endpoint of a connection – as a file descriptor (file handle), because of the Unix philosophy that "everything is a file" and the analogies between connections and files: you can read, write, open, and close both. In practice, the differences make the analogy strained, and one instead sends and receives on a connection.

The API evolved with little modification from a de facto standard into a component of the POSIX specification. Therefore, the term POSIX sockets is essentially synonymous with Berkeley sockets. 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. Only in 1989, however, could UC Berkeley release versions of its 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 or POSIX socket interface. It became the standard interface for connecting to the Internet. Even the Winsock implementation for MS Windows, developed by unaffiliated developers, closely follows the standard.

BSD and POSIX sockets

As the Berkeley socket API evolved and ultimately yielded the POSIX socket API,[1] certain functions were deprecated or removed and replaced by others. The POSIX API is also designed to be reentrant.

Action BSD POSIX
Conversion from text address to packed address inet_aton inet_pton
Conversion from packed address to text address inet_ntoa inet_ntop
Forward lookup for host name/service gethostbyname, gethostbyaddr, getservbyname, getservbyport getaddrinfo
Reverse lookup for host name/service gethostbyaddr, getservbyport getnameinfo

C and other programming languages

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.[2]

Alternatives

The STREAMS-based Transport Layer Interface (TLI) API offers an alternative to the socket API. However, recent systems that provide the TLI API also provide the Berkeley socket API.

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:

sys/socket.h
Core socket functions and data structures.
netinet/in.h
AF_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.h
PF_UNIX and PF_LOCAL address family. Used for local communication between programs running on the same computer.
arpa/inet.h
Functions for manipulating numeric IP addresses.
netdb.h
Functions for translating protocol names and host names into numeric addresses. Searches local data as well as name services.

Socket API functions

Flow diagram of client-server transaction using sockets with the Transmission Control Protocol (TCP).

This list is a summary of functions or methods provided by the Berkeley sockets API library:

socket()

The function socket() creates an endpoint for communication and returns a file descriptor for the socket. socket() takes three arguments:

Prototype

int socket(int domain, int type, int protocol)

The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor.

bind()

bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts. bind() takes three arguments:

Prototype

int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);

Bind() returns 0 on success and -1 if an error occurs.

listen()

After a socket has been associated with an address, listen() prepares it for incoming connections. However, this is only necessary for the stream-oriented (connection-oriented) data modes, i.e., for socket types (SOCK_STREAM, SOCK_SEQPACKET). listen() requires two arguments:

Prototype

int listen(int sockfd, int backlog);

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 (cf. select() function) and must initialize the connection using the accept() function. The accept() function creates a new socket for each connection and removes the connection from the listen queue. It takes the following arguments:

Prototype

int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen)

The accept() function returns the new socket descriptor for the accepted connection, or -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()

Prototype

int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen)

The connect() system call 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 the BSD-derived systems, the state of a socket descriptor is undefined if the call to connect() fails (as it is specified in the Single Unix Specification), thus, portable applications should close the socket descriptor immediately and obtain a new descriptor with socket(), in the case the call to connect() fails.[3]

gethostbyname() and gethostbyaddr()

The gethostbyname() and gethostbyaddr() functions are used to resolve host names and addresses in the domain name system or the local host's other resolver mechanisms (e.g., /etc/hosts lookup). They return a pointer to an object of type struct hostent, which describes an Internet Protocol host. The functions take the following arguments:

Prototype
 struct hostent *gethostbyname(const char *name)
 struct hostent *gethostbyaddr(const void *addr, int len, int type)

The functions return a NULL pointer in case of error, in which case the external integer h_errno 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 (supporting IPv6) have been defined. These new function are getaddrinfo() and getnameinfo(), and are based on a new addrinfo data structure.

Protocol and address families

The socket API is a general interface for Unix networking and allows the use of various network protocols and addressing architectures.

The following lists a sampling of protocol families (preceded by the standard symbolic identifier) defined in a modern Linux or BSD implementation:

PF_LOCAL, PF_UNIX, PF_FILE 
Local to host (pipes and file-domain)
PF_INET 
Internet Protocol version 4
PF_AX25 
Amateur Radio AX.25
PF_IPX 
Novell's Internetwork Packet Exchange
PF_APPLETALK 
Appletalk
PF_NETROM 
Amateur radio NetROM (related to AX.25)
PF_BRIDGE 
Multiprotocol bridge
PF_ATMPVC 
Asynchronous Transfer Mode Permanent Virtual Circuits
PF_ATMSVC 
Asynchronous Transfer Mode Switched Virtual Circuits
PF_INET6 
Internet Protocol version 6
PF_DECnet 
Reserved for DECnet project
PF_NETBEUI 
Reserved for 802.2LLC project
PF_SECURITY 
Security callback pseudo AF
PF_KEY  
PF_KEY key management API
PF_NETLINK, PF_ROUTE 
routing API
PF_PACKET 
Packet capture sockets
PF_ECONET 
Acorn Econet
PF_SNA 
Linux IBM Systems Network Architecture (SNA) Project
PF_IRDA 
IrDA sockets
PF_PPPOX 
PPP over X sockets
PF_WANPIPE 
Sangoma Wanpipe API sockets
PF_BLUETOOTH 
Bluetooth sockets

A socket for communications using any family is created with the socket() function, by specifying the desired protocol family (PF_-identifier) as an argument.

The original design concept of the socket interface distinguished between protocol types (families) 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 AF instead of PF. The AF-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 AF-constants were defined by the corresponding protocol identifier, leaving the distinction between AF and PF constants as a technical argument of no practical consequence. Indeed, much confusion exists in the proper usage of both forms.[4]

The POSIX.1—2008 specification doesn't specify any PF-constants, but only AF-constants[5]

Raw sockets

Raw sockets 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.[6] 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:

Blocking and non-blocking mode

Berkeley sockets can operate in one of two modes: blocking or non-blocking.

A blocking socket does not return control until it has sent (or received) 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.[7] 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 fcntl() or ioctl() functions.

Terminating sockets

The operating system does not release the resources allocated to a socket until a close() call occurs on the socket descriptor. This is especially important if the connect() call fails and may be retried. Each successful call to socket() must have a matching call to close() in all possible execution paths. The header file <unistd.h> defines the close function.

When the close() system call is initiated by an application, only the interface to the socket is destroyed, not the socket itself. It is the kernel's responsibility to destroy the socket internally. Sometimes, a socket may enter a TIME_WAIT state, on the server side, for up to 4 minutes.[8]

On SVR4 systems use of close() may discard data. The use of shutdown() or SO_LINGER may be required on these systems to guarantee delivery of all data.[9]

Client-server example using TCP

The Transmission Control Protocol (TCP) 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 socket() function with the parameters for the protocol family (PF INET, PF_INET6), the socket mode for Stream Sockets (SOCK_STREAM), and the IP protocol identifier for TCP (IPPROTO_TCP).

Server

Setting up a simple TCP server involves the following steps:

  1. Creating a TCP socket, with a call to socket().
  2. Binding the socket to the listen port, with a call to bind(). Before calling bind(), a programmer must declare a sockaddr_in structure, clear it (with memset()), and the sin_family (AF_INET), and fill its sin_port (the listening port, in network byte order) fields. Converting a short int to network byte order can be done by calling the function htons() (host to network short).
  3. Preparing the socket to listen for connections (making it a listening socket), with a call to listen().
  4. Accepting incoming connections, via a call to accept(). This blocks until an incoming connection is received, and then returns a socket descriptor for the accepted connection. The initial descriptor remains a listening descriptor, and accept() can be called again at any time with this socket, until it is closed.
  5. Communicating with the remote host, which can be done through send() and recv() or write() and read().
  6. Eventually closing each socket that was opened, once it is no longer needed, using close().

The following program creates a TCP server on port number 1100:

  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>
  
  int main(void)
  {
    struct sockaddr_in sa;
    int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (SocketFD == -1) {
      perror("cannot create socket");
      exit(EXIT_FAILURE);
    }
  
    memset(&sa, 0, sizeof sa);
  
    sa.sin_family = AF_INET;
    sa.sin_port = htons(1100);
    sa.sin_addr.s_addr = htonl(INADDR_ANY);
  
    if (bind(SocketFD,(struct sockaddr *)&sa, sizeof sa) == -1) {
      perror("bind failed");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }
  
    if (listen(SocketFD, 10) == -1) {
      perror("listen failed");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }
  
    for (;;) {
      int ConnectFD = accept(SocketFD, NULL, NULL);
  
      if (0 > ConnectFD) {
        perror("accept failed");
        close(SocketFD);
        exit(EXIT_FAILURE);
      }
  
      /* perform read write operations ... 
      read(ConnectFD, buff, size)
      */
  
      if (shutdown(ConnectFD, SHUT_RDWR) == -1) {
        perror("shutdown failed");
        close(ConnectFD);
        close(SocketFD);
        exit(EXIT_FAILURE);
      }
      close(ConnectFD);
    }

    close(SocketFD);
    return EXIT_SUCCESS;  
}

Client

Programming a TCP client application involves the following steps:

  1. Creating a TCP socket, with a call to socket().
  2. Connecting to the server with the use of connect(), passing a sockaddr_in structure with the sin_family set to AF_INET, sin_port set to the port the endpoint is listening (in network byte order), and sin_addr set to the IP address of the listening server (also in network byte order.)
  3. Communicating with the server by using send() and recv() or write() and read().
  4. Terminating the connection and cleaning up with a call to close().
  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>
  #include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <unistd.h>
  
  int main(void)
  {
    struct sockaddr_in sa;
    int res;
    int SocketFD;

    SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (SocketFD == -1) {
      perror("cannot create socket");
      exit(EXIT_FAILURE);
    }
  
    memset(&sa, 0, sizeof sa);
  
    sa.sin_family = AF_INET;
    sa.sin_port = htons(1100);
    res = inet_pton(AF_INET, "192.168.1.3", &sa.sin_addr);

    if (connect(SocketFD, (struct sockaddr *)&sa, sizeof sa) == -1) {
      perror("connect failed");
      close(SocketFD);
      exit(EXIT_FAILURE);
    }
  
    /* perform read write operations ... */
  
    (void)shutdown(SocketFD, SHUT_RDWR);
  
    close(SocketFD);
    return EXIT_SUCCESS;
  }

Client-server example using UDP

The User Datagram Protocol (UDP) 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 (Datagram Sockets).

UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports.

Server

An application may set up a UDP server on port 7654 as follows. This infinite loop receives any UDP datagrams to port 7654 using recvfrom().

 1 #include <stdio.h>
 2 #include <errno.h>
 3 #include <string.h>
 4 #include <sys/socket.h>
 5 #include <sys/types.h>
 6 #include <netinet/in.h>
 7 #include <unistd.h> /* for close() for socket */ 
 8 #include <stdlib.h>
 9 
10 int main(void)
11 {
12   int sock;
13   struct sockaddr_in sa; 
14   char buffer[1024];
15   ssize_t recsize;
16   socklen_t fromlen;
17 
18   memset(&sa, 0, sizeof sa);
19   sa.sin_family = AF_INET;
20   sa.sin_addr.s_addr = htonl(INADDR_ANY);
21   sa.sin_port = htons(7654);
22   fromlen = sizeof(sa);
23 
24   sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
25   if (bind(sock, (struct sockaddr *)&sa, sizeof sa) == -1) {
26     perror("error bind failed");
27     close(sock);
28     exit(EXIT_FAILURE);
29   }
30 
31   for (;;) {
32     recsize = recvfrom(sock, (void*)buffer, sizeof buffer, 0, (struct sockaddr*)&sa, &fromlen);
33     if (recsize < 0) {
34       fprintf(stderr, "%s\n", strerror(errno));
35       exit(EXIT_FAILURE);
36     }
37     printf("recsize: %d\n ", (int)recsize);
38     sleep(1);
39     printf("datagram: %.*s\n", (int)recsize, buffer);
40   }
41 }

Client

A simple demonstration of sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 and port 7654 might look like this:

 1 #include <stdlib.h>
 2 #include <stdio.h>
 3 #include <errno.h>
 4 #include <string.h>
 5 #include <sys/socket.h>
 6 #include <sys/types.h>
 7 #include <netinet/in.h>
 8 #include <unistd.h>
 9 #include <arpa/inet.h>
10 
11 int main(void)
12 {
13   int sock;
14   struct sockaddr_in sa;
15   int bytes_sent;
16   char buffer[200];
17  
18   strcpy(buffer, "hello world!");
19  
20   /* create an Internet, datagram, socket using UDP */
21   sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
22   if (sock == -1) {
23       /* if socket failed to initialize, exit */
24       printf("Error Creating Socket");
25       exit(EXIT_FAILURE);
26     }
27  
28   /* Zero out socket address */
29   memset(&sa, 0, sizeof sa);
30   
31   /* The address is IPv4 */
32   sa.sin_family = AF_INET;
33  
34    /* IPv4 adresses is a uint32_t, convert a string representation of the octets to the appropriate value */
35   sa.sin_addr.s_addr = inet_addr("127.0.0.1");
36   
37   /* sockets are unsigned shorts, htons(x) ensures x is in network byte order, set the port to 7654 */
38   sa.sin_port = htons(7654);
39  
40   bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, sizeof sa);
41   if (bytes_sent < 0) {
42     printf("Error sending packet: %s\n", strerror(errno));
43     exit(EXIT_FAILURE);
44   }
45  
46   close(sock); /* close the socket */
47   return 0;
48 }

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

Caveats

For TCP connections, the operating system may have to retransmit the data given to it with a write() call. However, the user space program is free to delete the data buffer passed to write() after write() returns. This implies that the operating system must make a copy of the data which can lead to a considerable CPU load in high throughput/performance applications. Other APIs, such as those supporting RDMA require that the data buffer is not released until the acknowledgement from the remote end has been received and thus make it possible to have zero memory copy operations.

References

  1. "— POSIX.1-2008 specification". Opengroup.org. Retrieved 2012-07-26.
  2. E. g. in the Ruby programming language ruby-doc::Socket
  3. 2013, Stevens & Rago 607.
  4. UNIX Network Programming Volume 1, Third Edition: The Sockets Networking API, W. Richard Stevens, Bill Fenner, Andrew M. Rudoff, Addison Wesley, 2003.
  5. "The Open Group Base Specifications Issue 7". Pubs.opengroup.org. Retrieved 2012-07-26.
  6. https://msdn.microsoft.com/en-us/library/windows/desktop/ms740548(v=vs.85).aspx
  7. "Beej's Guide to Network Programming". Beej.us. 2007-05-05. Retrieved 2012-07-26.
  8. "terminating sockets". Softlab.ntua.gr. Retrieved 2012-07-26.
  9. "ntua.gr - Programming UNIX Sockets in C - Frequently Asked Questions: Questions regarding both Clients and Servers (TCP/SOCK_STREAM)". Softlab.ntua.gr. Retrieved 2012-07-26.

The de jure standard definition of the Sockets interface is contained in the POSIX standard, known as:

Information about this standard and ongoing work on it is available from the Austin website.

The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542.

External links

This article is based on material taken from the Free On-line Dictionary of Computing prior to 1 November 2008 and incorporated under the "relicensing" terms of the GFDL, version 1.3 or later.


This article is issued from Wikipedia - version of the Friday, April 22, 2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.