Berkeley sockets
Encyclopedia : B : BE : BER : Berkeley sockets
The Berkeley sockets application programming interface (API) comprises a library for developing applications in the C programming language that perform inter-process communication, most commonly across a computer network.
Berkeley sockets (also known as the BSD socket API) originated with the 4.2BSD Unix operating system (released in 1983) as an API. Only in 1989, however, could UC Berkeley release versions of its operating system and networking library free from the licensing constraints of AT&T's copyright-protected Unix.
The Berkeley socket API forms the de facto standard abstraction for network sockets. Most other programing languages use a similar interface as the C API.
The STREAMS-based Transport Layer Interface (TLI) API offers an alternative to the socket API. However, the Berkeley socket API predominates convincingly in popularity and in the number of implementations.
Berkeley socket interface
The Berkeley socket interface, an API, allows communications between hosts or between processes on one computer, using the concept of a socket. It can work with many different I/O devices and drivers, although support for these depends on the operating-system implementation. This interface implementation is implicit for TCP/IP, and it is therefore one of the fundamental technologies underlying the Internet. It was first developed at the University of California, Berkeley for use on Unix systems. All modern operating systems now have some implementation of the Berkeley socket interface, as it has become the standard interface for connecting to the Internet.Programmers can make the socket interfaces accessible at three different levels, most powerfully and fundamentally at the RAW socket level. Very few applications need the degree of control over outgoing communications that this provides, so RAW sockets support was intended to be available only on computers used for developing Internet-related technologies. In recent years, most operating systems have implemented support for it anyway, including Windows XP.
The header files
The Berkeley socket development library has many associatedheader files. They include:
- ;
- : Definitions for the most basic of socket structures with the BSD socket API
- ;
- : Basic data types associated with structures within the BSD socket API
- ;
- : Definitions for the socketaddr_in and other base data structures.
- ;
- : Definitions and data type declarations for SOCK_UNIX streams
TCP
TCP provides the concept of a connection. A process creates a TCP socket by calling thesocket() function with the parameters PF_INET or PF_INET6 and SOCK_STREAM.Server
Setting up a simple TCP server involves the following steps:- Creating a TCP socket, with a call to
socket(). - Binding the socket to the listen port, with a call to
bind(). Before callingbind(), a programmer must declare asockaddr_instructure, clear it (withbzero()ormemset()), and thesin_family(AF_INETorAF_INET6), and fill itssin_port(the listening port, in network byte order) fields. Converting ashort intto network byte order can be done by calling the functionhtons()(host to network short). - Preparing the socket to listen for connections (making it a listening socket), with a call to
listen(). - 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, andaccept()can be called again at any time with this socket, until it is closed. - Communicating with the remote host, which can be done through
send()andrecv(). - Eventually closing each socket that was opened, once it is no longer needed, using
close(). Note that if there were any calls tofork(), each process must close the sockets it knew about (the kernel keeps track of how many processes have a descriptor open), and two processes should not use the same socket at once.
Client
Setting up a TCP client involves the following steps:- Creating a TCP socket, with a call to
socket(). - Connecting to the server with the use of
connect, passing asockaddr_instructure with thesin_familyset toAF_INETorAF_INET6,sin_portset to the port the endpoint is listening (in network byte order), andsin_addrset to the IPv4 or IPv6 address of the listening server (also in network byte order.) - Communicating with the server by
send()ing andrecv()ing. - Terminating the connection and cleaning up with a call to
close(). Again, if there were any calls tofork(), each process mustclose()the socket.
UDP
UDP consists of a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, become duplicated and arrive more than once, or even not arrive at all. Due to the minimal guarantees involved, UDP has considerably less overhead than TCP. Being connectionless means that there is no concept of a stream or connection between two hosts, instead, data arrives in datagrams.UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports.
Server
Code may set up a UDP server on port 7654 as follows:
sock = socket(PF_INET,SOCK_DGRAM,0);bind() binds the socket to an address/port pair. listen() sets the length of the new connections queue.sa.sin_addr.s_addr = INADDR_ANY; sa.sin_port = htons(7654);
bound = bind(sock,(struct sockaddr *)&sa, sizeof(struct sockaddr)); if (bound < 0) fprintf(stderr, "bind(): %s\n",strerror(errno)); listen(sock,3);
while (1)This infinite loop receives any UDP datagrams to port 7654 using recvfrom(). It uses the parameters:
- socket
- pointer to buffer for data
- size of buffer
- flags (same as in read or other receive socket function)
- address struct of sending peer
- length of address struct of sending peer.
Client
A simple demo to send an UDP packet containing "Hello World!" to address 127.0.0.1, port 7654 might look like this:
#includeIn this code,#include #include #include #include #include int main(int argc, char *argv[])
buffer provides a pointer to the data to send, and buffer_length specifies the size of the buffer contents.Functions
socket()
socket() creates an endpoint for communication and returns a descriptor. socket() takes three arguments:
- domain, which specifies the protocol family of the created socket. For example:
- *
PF_INETfor network protocol IPv4 or - *
PF_INET6for IPv6). - type, one of:
- *
SOCK_STREAM(reliable stream-oriented service) - *
SOCK_DGRAM(datagram service) - *
SOCK_SEQPACKET(reliable sequenced packet service), or - *
SOCK_RAW(raw protocols atop the network layer). - protocol, usually set to 0 to represent the default transport protocol for the specified domain and type values (TCP for
PF_INETorPF_INET6andSOCK_STREAM, UDP for thosePF_values andSOCK_DGRAM), but which can also explicitly specify a protocol.
Prototype:
int socket(int domain, int type, int protocol);gethostbyname() and gethostbyaddr()
Prototypes:
struct hostent *gethostbyname(const char *name);
struct hostent *gethostbyaddr(const void *addr, int len, int type);
connect()
connect()
It returns an integer representing the error code: 0 represents success, while -1 represents an error.
Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets.
Prototype:
int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen);bind()
bind() assigns a socket an address. When a socket is created using socket(), it is given an address family, but not assigned an address. Before a socket may accept incoming connections, it must be bound. bind() takes three arguments:
sockfd, a descriptor representing the socket to perform the bind onmy_addr, a pointer to asockaddrstructure representing the address to bind to.addrlen, asocklen_tfield representing the length of thesockaddrstructure.
Prototype:
int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);listen()
listen() prepares a bound socket to accept incoming connections. This function is only applicable to the SOCK_STREAM and SOCK_SEQPACKET socket types. It takes 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.
Prototype:
int listen(int sockfd, int backlog);accept()
Programmers useaccept() to accept a connection request from a remote host. It takes the following arguments:
sockfd, the descriptor of the listening socket to accept the connection from.cliaddr, a pointer to the sockaddr structure thataccept()should put the client's address information into.addrlen, a pointer to thesocklen_tinteger that will indicate toaccept()how large the sockaddr structure pointed to bycliaddris. Whenaccept()returns, thesocklen_tinteger then indicates how many bytes of thecliaddrstructure were actually used.
Prototype:
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);Blocking vs. nonblocking
Berkeley sockets can operate in one of two modes: blocking or non-blocking. A blocking socket will not "return" until it has sent (or received) all the data specified for the operation. This may cause problems if a socket continues to listen: a program may hang as the socket waits for data that may never arrive.
A socket is typically set to blocking or nonblocking mode using the fcntl() or ioctl() functions.
Cleaning up
The system will not release the resources allocated by the socket() call until a close() call occurs. This is especially important if the connect() call fails and may be retried. Each call to socket() must have a matching call to close() in all possible execution paths.
See also
- Computer network
- Winsock, the Berkeley sockets-based application programming interface for networking on Microsoft Windows
External links
- [Unix Manual Pages:]
- *[accept(2)]
- *[connect(2)]
- [Beej's Guide to Network Programming]
- [UnixSocket FAQ]
- [Porting Berkley Socket programs to Winsock]
- This article was originally based on material from the Free On-line Dictionary of Computing, which is [Foldoc licenselicensed] under the GFDL.
From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.
