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.
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.
header files. They include:
socket() function with the parameters PF_INET or PF_INET6 and SOCK_STREAM.
socket().
bind(). Before calling bind(), a programmer must declare a sockaddr_in structure, clear it (with bzero() or memset()), and the sin_family (AF_INET or AF_INET6), 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).
listen().
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.
send() and recv().
close(). Note that if there were any calls to fork(), 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.
socket().
connect, passing a sockaddr_in structure with the sin_family set to AF_INET or AF_INET6, sin_port set to the port the endpoint is listening (in network byte order), and sin_addr set to the IPv4 or IPv6 address of the listening server (also in network byte order.)
send()ing and recv()ing.
close(). Again, if there were any calls to fork(), each process must close() the socket.
UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports.
Code may set up a UDP server on port 7654 as follows:
sock = socket(PF_INET,SOCK_DGRAM,0); 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);
bind() binds the socket to an address/port pair. listen() sets the length of the new connections queue.
while (1) { printf ("recv test....\n"); recsize = recvfrom(sock, (void *)hz, 100, 0, (struct sockaddr *)&sa, fromlen); printf ("recsize: %d\n ",recsize); if (recsize < 0) fprintf(stderr, "%s\n", strerror(errno)); sleep(1); printf("datagram: %s\n",hz); }
This infinite loop receives any UDP datagrams to port 7654 using recvfrom(). It uses the parameters:
A simple demo to send an UDP packet containing "Hello World!" to address 127.0.0.1, port 7654 might look like this:
#include
In this code, buffer provides a pointer to the data to send, and buffer_length specifies the size of the buffer contents.
socket() creates an endpoint for communication and returns a descriptor. socket() takes three arguments:
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).
PF_INET or PF_INET6 and SOCK_STREAM, UDP for those PF_ values and SOCK_DGRAM), but which can also explicitly specify a protocol.
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly-assigned descriptor.
int socket(int domain, int type, int protocol);
struct hostent *gethostbyname(const char *name);
struct hostent *gethostbyaddr(const void *addr, int len, int type);
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.
int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen);
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 on
my_addr, a pointer to a sockaddr structure representing the address to bind to.
addrlen, a socklen_t field representing the length of the sockaddr structure.
int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen);
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.
int listen(int sockfd, int backlog);
accept() 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 that accept() should put the client's address information into.
addrlen, a pointer to the socklen_t integer that will indicate to accept() how large the sockaddr structure pointed to by cliaddr is. When accept() returns, the socklen_t integer then indicates how many bytes of the cliaddr structure were actually used.
The function returns a socket corresponding to the accepted connection, or -1 if an error occurs.
int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);
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.
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.
Network-related software | Application programming interfaces | Inter-process communication
This article is licensed under the GNU Free Documentation License.
It uses material from the
"Berkeley sockets".
Home Page • arts • business • computers • games • health • hospitals • home • kids & teens • news • physicians • recreation• reference • regional • science • shopping • society • sports • world