Berkeley Sockets
   HOME

TheInfoList



OR:

Berkeley sockets is an
application programming interface An application programming interface (API) is a way for two or more computer programs to communicate with each other. It is a type of software interface, offering a service to other pieces of software. A document or standard that describes how t ...
(API) for
Internet socket The Internet (or internet) is the global system of interconnected computer networks that uses the Internet protocol suite (TCP/IP) to communicate between networks and devices. It is a '' network of networks'' that consists of private, pub ...
s and
Unix domain socket A Unix domain socket aka UDS or IPC socket ( inter-process communication socket) is a data communications endpoint for exchanging data between processes executing on the same host operating system. It is also referred to by its address family AF_U ...
s, used for
inter-process communication In computer science, inter-process communication or interprocess communication (IPC) refers specifically to the mechanisms an operating system provides to allow the processes to manage shared data. Typically, applications can use IPC, categori ...
(IPC). It is commonly implemented as a
library A library is a collection of materials, books or media that are accessible for use and not just for display purposes. A library provides physical (hard copies) or digital access (soft copies) materials, and may be a physical location or a vir ...
of linkable modules. It originated with the 4.2BSD Unix operating system, which was released in 1983. A
socket Socket may refer to: Mechanics * Socket wrench, a type of wrench that uses separate, removable sockets to fit different sizes of nuts and bolts * Socket head screw, a screw (or bolt) with a cylindrical head containing a socket into which the hexag ...
is an abstract representation (
handle A handle is a part of, or attachment to, an object that allows it to be grasped and manipulated by hand. The design of each type of handle involves substantial ergonomic issues, even where these are dealt with intuitively or by following tra ...
) for the local endpoint of a network communication path. The Berkeley sockets API represents it as a
file descriptor In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically have ...
(
file handle In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically hav ...
) in the
Unix philosophy The Unix philosophy, originated by Ken Thompson, is a set of cultural norms and philosophical approaches to minimalist, modular software development. It is based on the experience of leading developers of the Unix operating system. Early Unix dev ...
that provides a common interface for input and output to
streams A stream is a continuous body of water, body of surface water Current (stream), flowing within the stream bed, bed and bank (geography), banks of a channel (geography), channel. Depending on its location or certain characteristics, a stream ...
of data. Berkeley sockets evolved with little modification from a ''de facto'' standard into a component of the
POSIX The Portable Operating System Interface (POSIX) is a family of standards specified by the IEEE Computer Society for maintaining compatibility between operating systems. POSIX defines both the system- and user-level application programming interf ...
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 The Berkeley Software Distribution or Berkeley Standard Distribution (BSD) is a discontinued operating system based on Research Unix, developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berk ...
.


History and implementations

Berkeley sockets originated with the 4.2BSD
Unix Unix (; trademarked as UNIX) is a family of multitasking, multiuser computer operating systems that derive from the original AT&T Unix, whose development started in 1969 at the Bell Labs research center by Ken Thompson, Dennis Ritchie, and ot ...
operating system An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. Time-sharing operating systems schedule tasks for efficient use of the system and may also in ...
, released in 1983, as a programming interface. Not until 1989, however, could the
University of California, Berkeley The University of California, Berkeley (UC Berkeley, Berkeley, Cal, or California) is a public land-grant research university in Berkeley, California. Established in 1868 as the University of California, it is the state's first land-grant u ...
release versions of the operating system and networking library free from the licensing constraints of
AT&T Corporation AT&T Corporation, originally the American Telephone and Telegraph Company, is the subsidiary of AT&T Inc. that provides voice, video, data, and Internet telecommunications and professional services to businesses, consumers, and government agen ...
'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 The Internet (or internet) is the global system of interconnected computer networks that uses the Internet protocol suite (TCP/IP) to communicate between networks and devices. It is a '' network of networks'' that consists of private, pub ...
. Even the
Winsock In computing, the Windows Sockets API (WSA), later shortened to Winsock, is an application programming interface (API) that defines how Windows network application software should access network services, especially TCP/IP. It defines a standar ...
implementation for MS Windows, created by unaffiliated developers, closely follows the standard. The BSD sockets API is written in the
C programming language ''The C Programming Language'' (sometimes termed ''K&R'', after its authors' initials) is a computer programming book written by Brian Kernighan and Dennis Ritchie, the latter of whom originally designed and implemented the language, as well as ...
. Most other programming languages provide similar interfaces, typically written as a
wrapper library Wrapper libraries (or library wrappers) consist of a thin layer of code (a "shim") which translates a library's existing interface into a compatible interface. This is done for several reasons: * To refine a poorly designed or complicated interfac ...
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 and supports IPv6.


Alternatives

The
STREAMS A stream is a continuous body of water, body of surface water Current (stream), flowing within the stream bed, bed and bank (geography), banks of a channel (geography), channel. Depending on its location or certain characteristics, a stream ...
-based
Transport Layer Interface In computer networking, the Transport Layer Interface (TLI) was the networking API provided by AT&T UNIX System V Release 3 (SVR3) in 1987 and continued into Release 4 (SVR4). TLI was the System V counterpart to the BSD sockets programming inter ...
(TLI) 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 Genode is a free and open-source software operating system (OS) framework consisting of a microkernel abstraction layer and a set of user space components. The framework is notable as one of the few open-source operating systems not derived from ...
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:


Socket API functions

The Berkeley socket API typically provides the following functions: * ''socket()'' creates a new socket of a certain 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 IP address and a port number. * ''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()'', ''recv()'', ''sendto()'', and ''recvfrom()'' are used for sending and receiving data. The standard functions ''write()'' and ''read()'' may also be used. * ''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. * ''getaddrinfo()'' and ''freeaddrinfo()'' are used to resolve host names and addresses. IPv4, IPv6. * ''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.


socket

The function ''socket()'' creates an endpoint for communication and returns a
file descriptor In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier (handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically have ...
for the socket. It uses three arguments: * , which specifies the protocol family of the created socket. For example: ** for network protocol
IPv4 Internet Protocol version 4 (IPv4) is the fourth version of the Internet Protocol (IP). It is one of the core protocols of standards-based internetworking methods in the Internet and other packet-switched networks. IPv4 was the first version de ...
(IPv4-only) ** for
IPv6 Internet Protocol version 6 (IPv6) is the most recent version of the Internet Protocol (IP), the communication protocol, communications protocol that provides an identification and location system for computers on networks and routes traffic ...
(and in some cases,
backward compatible Backward compatibility (sometimes known as backwards compatibility) is a property of an operating system, product, or technology that allows for interoperability with an older legacy system, or with input designed for such a system, especially in ...
with IPv4) ** for local socket (using a special filesystem node) * , one of: ** (reliable stream-oriented service or
Stream Sockets A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programming ...
) ** (datagram service or
Datagram Sockets A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programming ...
) ** (reliable sequenced packet service) ** (raw protocols atop the network layer) * specifying the actual transport protocol to use. The most common are , , , . These protocols are specified in file ''netinet/in.h''. The value may be used to select a default protocol from the selected domain and type. 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: *sockfd, a descriptor representing the socket *my_addr, a pointer to a ''sockaddr'' structure representing the address to bind to. *addrlen, a field of type ''socklen_t'' specifying the size of the ''sockaddr'' structure. ''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: * 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..


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 function ''accept()''. It creates a new socket for each connection and removes the connection from the listening queue. The function has 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 contains the size (in bytes) of the structure. ''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 Connection-oriented communication is a network communication mode in telecommunications and computer networking, where a communication session or a semi-permanent connection is established before any useful data can be transferred. The establish ...
protocol, this establishes a connection. Certain types of protocols are connectionless, most notably the
User Datagram Protocol In computer networking, the User Datagram Protocol (UDP) is one of the core communication protocols of the Internet protocol suite used to send messages (transported as datagrams in packets) to other hosts on an Internet Protocol (IP) network. ...
. 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 (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 functions ''gethostbyname()'' and ''gethostbyaddr()'' are used to resolve host names and addresses in the
domain name system The Domain Name System (DNS) is a hierarchical and distributed naming system for computers, services, and other resources in the Internet or other Internet Protocol (IP) networks. It associates various information with domain names assigned to ...
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 The Internet Protocol (IP) is the network layer communications protocol in the Internet protocol suite for relaying datagrams across network boundaries. Its routing function enables internetworking, and essentially establishes the Internet. IP h ...
host. The functions use the following arguments: * name specifies the DNS name of the host. * addr specifies a pointer to a struct in_addr containing the address of the host. * len specifies the length, in bytes, of addr. * type 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 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 functions 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 (preceded by the standard symbolic identifier) defined in a modern
Linux Linux ( or ) is a family of open-source Unix-like operating systems based on the Linux kernel, an operating system kernel first released on September 17, 1991, by Linus Torvalds. Linux is typically packaged as a Linux distribution, which ...
or
BSD The Berkeley Software Distribution or Berkeley Standard Distribution (BSD) is a discontinued operating system based on Research Unix, developed and distributed by the Computer Systems Research Group (CSRG) at the University of California, Berk ...
implementation: A socket for communications is created with the function, by specifying the desired protocol family (-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 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

Raw socket A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programming ...
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 A modern computer operating system usually segregates virtual memory into user space and kernel space. Primarily, this separation serves to provide memory protection and hardware protection from malicious or errant software behaviour. Kernel ...
and aid in debugging of the protocol stack. Raw sockets are used by some services, such as ICMP, that operate at the
Internet Layer The internet layer is a group of internetworking methods, protocols, and specifications in the Internet protocol suite that are used to transport network packets from the originating host across network boundaries; if necessary, to the destinat ...
of the TCP/IP model.


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. 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 condition A race condition or race hazard is the condition of an electronics, software, or other system where the system's substantive behavior is dependent on the sequence or timing of other uncontrollable events. It becomes a bug when one or more of t ...
s due to variances in network link speed. A socket is typically set to blocking or non-blocking mode using the functions
fcntl In Unix and Unix-like computer operating systems, a file descriptor (FD, less frequently fildes) is a process-unique identifier ( handle) for a file or other input/output resource, such as a pipe or network socket. File descriptors typically hav ...
and
ioctl In computing, ioctl (an abbreviation of input/output control) is a system call for device-specific input/output operations and other operations which cannot be expressed by regular system calls. It takes a parameter specifying a request code; th ...
.


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 The Transmission Control Protocol (TCP) is one of the main protocols of the Internet protocol suite. It originated in the initial network implementation in which it complemented the Internet Protocol (IP). Therefore, the entire suite is commonly ...
(TCP) is a
connection-oriented Connection-oriented communication is a network communication mode in telecommunications and computer networking, where a communication session or a semi-permanent connection is established before any useful data can be transferred. The establish ...
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 A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programming ...
(), and the IP protocol identifier for TCP ().


Server

Establishing a TCP server involves the following basic steps: * Creating a TCP socket with a call to ''socket().'' * Binding the socket to the listening port (''bind()'') after setting the port number. * Preparing the socket to listen for connections (making it a listening socket), with a call to ''listen()''. * Accepting incoming connections (''accept()''). This blocks the process until an incoming connection is received, and 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. * Communicating with the remote host with the API functions ''send()'' and ''recv()'', as well as with the general-purpose functions ''write()'' and ''read()''. * Closing each socket that was opened after use with function ''close()'' The following program creates a TCP server listening on port number 1100: #include #include #include #include #include #include #include #include int main(void)


Client

Programming a TCP client application involves the following steps: * Creating a TCP socket. * Connecting to the server (''connect()''), by passing a structure with the set to , 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 remote host with the API functions ''send()'' and ''recv()'', as well as with the general-purpose functions ''write()'' and ''read()''. * Closing each socket that was opened after use with function ''close().'' #include #include #include #include #include #include #include #include int main(void)


Client-server example using UDP

The
User Datagram Protocol In computer networking, the User Datagram Protocol (UDP) is one of the core communication protocols of the Internet protocol suite used to send messages (transported as datagrams in packets) to other hosts on an Internet Protocol (IP) network. ...
(UDP) is a
connectionless Connectionless communication, often referred to as CL-mode communication,Information Processing Systems - Open Systems Interconnection, "Transport Service Definition - Addendum 1: Connectionless-mode Transmission", International Organization for ...
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 A network socket is a software structure within a network node of a computer network that serves as an endpoint for sending and receiving data across the network. The structure and properties of a socket are defined by an application programming ...
). 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 number 7654 as follows. The programs contains an infinite loop that receives UDP datagrams with function ''recvfrom()''. #include #include #include #include #include #include #include /* for close() for socket */ #include int main(void)


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. #include #include #include #include #include #include #include #include #include int main(void) In this code, ''buffer'' is a pointer to the data to be sent, and ''buffer_length'' specifies the size of the data.


References

The ''
de jure In law and government, ''de jure'' ( ; , "by law") describes practices that are legally recognized, regardless of whether the practice exists in reality. In contrast, ("in fact") describes situations that exist in reality, even if not legally ...
'' standard definition of the Sockets interface is contained in the POSIX standard, known as: *
IEEE The Institute of Electrical and Electronics Engineers (IEEE) is a 501(c)(3) professional association for electronic engineering and electrical engineering (and associated disciplines) with its corporate office in New York City and its operation ...
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 fro
the Austin website
The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542. *


External links


UNIX Programmer's Supplementary Documents (PSD: 20-1)

Beej's Guide to Network Programming
- 2007
Porting Berkeley Socket programs to Winsock
- Microsoft's documentation.

- 1996
Linux network programming
- ''
Linux Journal ''Linux Journal'' (''LJ'') is an American monthly technology magazine originally published by Specialized System Consultants, Inc. (SSC) in Seattle, Washington since 1994. In December 2006 the publisher changed to Belltown Media, Inc. in Houston ...
'', 1998 {{DEFAULTSORT:Berkeley Sockets Network socket Application programming interfaces Articles with example C code Berkeley Software Distribution