Berkeley sockets

From Free net encyclopedia

(Redirected from Berkeley Sockets)

The Berkeley sockets application programming interface (API) comprises a library for developing applications written in the C programming language that access a computer network.

Berkeley sockets (also known as the BSD socket API) originated with the 4.2BSD system (released in 1983) as an API, covered under the BSD license, for development of sockets. 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 operating system.

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.

An alternative to the socket API is the STREAMS-based Transport Layer Interface (TLI) API. However, the socket API is much more popular and much more widely implemented.

Contents

Berkeley socket interface

The Berkeley socket interface is an API that allows communications between hosts or between processes on one computer, using the concept of a socket. It is able to work with many different I/O devices and drivers, although support for this is dependent 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 at 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.

There are three different levels at which the socket interface can be made accessible, the most powerful and fundamental of which is RAW sockets. 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 associated header files. They include:

<sys/socket.h>
Definitions for the most basic of socket structures with the BSD socket API
<sys/types.h>
Basic data types associated with structures within the BSD socket API
<netinet/in.h>
Definitions for the socketaddr_in{} and other base data structures.
<sys/un.h>
Definitions and data type declarations for SOCK_UNIX streams

TCP

TCP provides the concept of a connection. A TCP socket is created by calling the socket() function with the parameters AF_INET or AF_INET6 and SOCK_STREAM, respectively.

Server

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 calling bind(), a sockaddr_in structure must be declared and cleared (with bzero()), and the sin_family (AF_INET or AF_INET6) and sin_port (the listening port, in network byte order) fields of it must be filled. Converting a short int to network byte order can be done by calling the function htons() (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, and accept() 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() and recv().
  • Eventually closing each socket that was opened, once it is no longer needed, using close(). It's worth noting 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.

Client

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 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.)
  • Communicating with the server by send()ing and recv()ing.
  • Terminating the connection and cleaning up with a call to close(). Again, if there any calls to fork(), each process must close() the socket.

UDP

UDP is a connectionless protocol with no guarantees on delivery. UDP packets may arrive out of order, be 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.

Server

A UDP server on port 7654 may be created as follows:

sock = socket(AF_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(). Its parameters are:

  • 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

  • TODO

Functions

socket()

socket() creates an endpoint for communication and returns a descriptor. Socket takes three arguments:

  • domain, which specifies the address family of the socket that is created (AF_INET, for example).
  • type, which is one of SOCK_STREAM (TCP), SOCK_DGRAM (UDP), or SOCK_RAW (RAW).
  • protocol, which is usually set to 0 to represent the default protocol for the specified domain and type.

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

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, the most common being user datagram protocol sockets. For these sockets, connect takes on a special meaning: The default target for sending and receiving data will be 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 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.

It returns 0 on success and -1 if an error occurs.

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.

Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is returned.

Prototype:

int listen(int sockfd, int backlog);

accept()

Programmers use accept() to accept a connection request from a remote host. Its arguments are:

  • 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.

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.

See also

External links

This article was originally based on material from the Free On-line Dictionary of Computing, which is licensed under the GFDL.