Next:6.0.3 The Sendto() call Up:6 The Socket API Previous:6.0.1 The Socket() call
6.0.2 The call
Here is the prototype of the system call:
The arguments to this call are basically the same as the standard socket call. The call reads ``one packet at a time''. It returns the length of the message written to the buffer pointed to by the argument (the second argument). Even if one packet worth of message does not ``fill up'' the buffer, will return immediately and will not read the second packet. However, if a message in a packet is too long to fit in the supplied buffer, the excess bytes are discarded.
By default, is blocking: when a process issues a that cannot be completed immediately (because there is no packet), the process is put to sleep waiting for a packet to arrive at the socket. Therefore, a call to will return immediately only if a packet is available on the socket.
When the argument of is set to , does not block if there is no data to be read, but returns immediately with a return value of 0 bytes. is defined in . In an actual UNIX system, socket descriptors are set to be non-blocking using with type , and returns errno when there is no data to be read on the non-blocking socket.
Next:6.0.3 The Sendto() call Up:6 The Socket API Previous:6.0.1 The Socket() call
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.
A socket is an abstract representation (handle) for the local endpoint of a network communication path. The Berkeley sockets API represents it as a file descriptor (file handle) 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. 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 Unixoperating 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.
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.
|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|
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.
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
This list is a summary of functions or methods provided by the Berkeley sockets API library:
- socket() creates a new socket of a certain socket type, identified by an integer number, and allocates system resources to it.
- bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local port number and IP address.
- listen() is used on the server side, and causes a bound TCP socket to enter listening state.
- connect() is used on the client side, and assigns a free local port number to a socket. In case of a TCP socket, it causes an attempt to establish a new TCP connection.
- accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection.
- send() and recv(), or write() and read(), or sendto() and recvfrom(), are used for sending and receiving data to/from a remote socket.
- close() causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated.
- gethostbyname() and gethostbyaddr() are used to resolve host names and addresses. IPv4 only.
- select() is used to suspend, waiting for one or more of a provided list of sockets to be ready to read, ready to write, or that have errors.
- poll() is used to check on the state of a socket in a set of sockets. The set can be tested to see if any socket can be written to, read from or if an error occurred.
- getsockopt() is used to retrieve the current value of a particular socket option for the specified socket.
- setsockopt() is used to set a particular socket option for the specified socket.
The function socket() creates an endpoint for communication and returns a file descriptor for the socket. socket() takes three arguments:
- , which specifies the protocol family of the created socket. For example:
- AF_INET for network protocol IPv4 (IPv4-only)
- AF_INET6 for IPv6 (and in some cases, backward compatible with IPv4)
- AF_UNIX for local socket (using a file)
- , one of:
- SOCK_STREAM (reliable stream-oriented service or Stream Sockets)
- SOCK_DGRAM (datagram service or Datagram Sockets)
- SOCK_SEQPACKET (reliable sequenced packet service)
- SOCK_RAW (raw protocols atop the network layer)
- specifying the actual transport protocol to use. The most common are IPPROTO_TCP, IPPROTO_SCTP, IPPROTO_UDP, IPPROTO_DCCP. These protocols are specified in file netinet/in.h. The value 0 may be used to select a default protocol from the selected domain and type.
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor.
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:
- sockfd, a descriptor representing the socket to perform the bind on.
- my_addr, a pointer to a sockaddr structure representing the address to bind to.
- addrlen, a socklen_t field specifying the size of the sockaddr structure.
Bind() returns 0 on success and -1 if an error occurs.
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:
- sockfd, a valid socket descriptor.
- backlog, an integer representing the number of pending connections that can be queued up at any one time. The operating system usually places a cap on this value.
Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is returned.
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:
- sockfd, the descriptor of the listening socket that has the connection queued.
- cliaddr, a pointer to a sockaddr structure to receive the client's address information.
- addrlen, a pointer to a socklen_t location that specifies the size of the client address structure passed to accept(). When accept() returns, this location indicates how many bytes of the structure were actually used.
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.
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.
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 , which describes an Internet Protocol host. The functions take the following arguments:
- specifies the name of the host. For example: www.wikipedia.org
- specifies a pointer to a containing the address of the host.
- specifies the length, in bytes, of .
- specifies the address family type (e.g., AF_INET) of the host address.
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 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:
A socket for communications using any family is created with the 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.
The POSIX.1—2008 specification doesn't specify any PF-constants, but only AF-constants
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. 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:
- TCP_NODELAY disables the Nagle algorithm.
- SO_KEEPALIVE enables periodic 'liveness' pings, if supported by the OS.
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. 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.
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 TIME_WAIT 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 (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 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).
Setting up a simple TCP server involves the following steps:
- Creating a TCP socket, with a call to .
- Binding the socket to the listen port, with a call to . Before calling , a programmer must declare a structure, clear it (with ), and the sin_family (), and fill its (the listening port, in network byte order) fields. Converting a short int to network byte order can be done by calling the function (host to network short).
- Preparing the socket to listen for connections (making it a listening socket), with a call to .
- Accepting incoming connections, via a call to . 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 can be called again at any time with this socket, until it is closed.
- Communicating with the remote host, which can be done through and or and .
- Eventually closing each socket that was opened, once it is no longer needed, using .
The following program creates a TCP server on port number 1100:
Programming a TCP client application involves the following steps:
- Creating a TCP socket, with a call to .
- Connecting to the server with the use of , passing a structure with the set to AF_INET, set to the port the endpoint is listening (in network byte order), and set to the IP address of the listening server (also in network byte order.)
- Communicating with the server by using and or and .
- Terminating the connection and cleaning up with a call to .
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.
An application may set up a UDP server on port number 7654 as follows. The programs contains an infinite loop that receives UDP datagrams using .
A simple client program for sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 and port number 7654 might look like this:
In this code, buffer is a pointer to the data to be sent, and buffer_length specifies the size of the data.
For TCP connections, the operating system may have to retransmit the data given to it with a call. However, the user space program is free to delete the data buffer passed to after 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.
The de jure standard definition of the Sockets interface is contained in the POSIX standard, known as:
- IEEE Std. 1003.1-2001 Standard for Information Technology—Portable Operating System Interface (POSIX).
- Open Group Technical Standard: Base Specifications, Issue 6, December 2001.
- ISO/IEC 9945:2002
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.
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.