- Berkeley sockets
The Berkeley sockets
application programming interface (API) comprises a library for developing applications in the C programming language that performinter-process communication , most commonly across acomputer network .Berkeley sockets (also known as the BSD socket API) originated with the 4.2BSD
Unix operating system (released in1983 ) as an API. Only in1989 , however, could UC Berkeley release versions of its operating system and networking library free from the licensing constraints ofAT&T 's copyright-protected Unix.The Berkeley socket API forms the "
de facto " standard abstraction for network sockets. Most other programming languages use an interface similar to 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 an "internet 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 theUniversity of California, Berkeley for use on Unix systems. All modern operating systems now have some implementation of the Berkeley socket interface, as it became 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 associated header files. They include:
:;
:: Core BSD socket functions and data structures.:;
:: PF_INET and PF_INET6 address/protocol families. Widely used on the Internet, these include IP addresses and TCP and UDP port numbers.:;
:: PF_UNIX/PF_LOCAL address family. Used for local communication between programs running on the same computer. Not used on networks.:;
:: Functions for manipulating numeric IP addresses.:;
:: Functions for translating protocol names and host names into numeric addresses. Searches local data as well as DNS.TCP
TCP provides the concept of a connection. A process creates a TCP socket by calling the
socket()
function with the parameters
orPF_INET PF_INET6
andSOCK_STREAM
(Stream Sockets ).Server
Setting up a simple TCP server involves the following steps:
* Creating a TCP socket, with a call tosocket()
.
* Binding the socket to the listen port, with a call tobind()
. Before callingbind()
, a programmer must declare asockaddr_in
structure, clear it (withmemset()
), and thesin_family
(PF_INET
orPF_INET6
), and fill itssin_port
(the listening port, innetwork byte order ) fields. Converting ashort int
to 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 tolisten()
.
* Accepting incoming connections, via a call toaccept()
. 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 throughsend()
andrecv()
orwrite()
andread()
.
* Eventually closing each socket that was opened, once it is no longer needed, usingclose()
. 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 tosocket()
.
* Connecting to the server with the use ofconnect()
, passing asockaddr_in
structure with thesin_family
set toPF_INET
orPF_INET6
,sin_port
set to the port the endpoint is listening (in network byte order), andsin_addr
set to the IPv4 or IPv6 address of the listening server (also in network byte order.)
* Communicating with the server by usingsend()
andrecv()
orwrite()
andread()
.
* Terminating the connection and cleaning up with a call toclose()
. 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 (Datagram Sockets ).UDP address space, the space of UDP port numbers (in ISO terminology, the
TSAP s), is completely disjoint from that of TCP ports.Server
Code may set up a UDP server on port 7654 as follows:
bind() binds the socket to an address/port pair.
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 a UDP packet containing "Hello World!" to address 127.0.0.1, port 7654 might look like this:
In this code,
buffer
provides a pointer to the data to send, andbuffer_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_INET
for network protocolIPv4 or
**PF_INET6
forIPv6 .
**PF_UNIX
for local socket (using a file).
* type, one of:
**SOCK_STREAM
(reliable stream-oriented service orStream Sockets )
**SOCK_DGRAM
(datagram service orDatagram Sockets )
**SOCK_SEQPACKET
(reliable sequenced packet service), or
**SOCK_RAW
(raw protocols atop the network layer).
* protocol, usually set toIPPROTO_IP
, which is defined as 0, to represent the defaulttransport protocol for the specified domain and type values (TCP forPF_INET
orPF_INET6
andSOCK_STREAM
, UDP for thosePF_
values andSOCK_DGRAM
), but which can also explicitly specify a protocol. These protocols are specified in. The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly-assigned descriptor.
Prototype
gethostbyname() and gethostbyaddr()
The
gethostbyname()
andgethostbyaddr()
functions each return a pointer to an object of type struct hostent, which describes an internet host referenced by name or by address, respectively. This structure contains either the information obtained from a name server (ex: named), or broken-out fields from a line in /etc/hosts. If the local name server is not running these routines do a lookup in /etc/hosts. The functions take the following arguments:* name, which specifies the name of the host. For example: www.wikipedia.org
* addr, which specifies a pointer to a struct in_addr containing the address of the host.
* len, which specifies the length, in bytes, of addr.
* type, which specifies the domain type of the host address. For example: PF_INETThe functions return a NULL pointer in case of error, in which case the external integer h_errno may be checked so see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid struct hostent * is returned.
Prototypes
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
bind()
bind()
assigns a socket an address. When a socket is created usingsocket()
, 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
*serv_addr
, a pointer to asockaddr
structure representing the address to bind to.
*addrlen
, asocklen_t
field representing the length of thesockaddr
structure.It returns 0 on success and -1 if an error occurs.Prototype
listen()
listen()
prepares a bound socket to accept incoming connections. This function is only applicable to theSOCK_STREAM
andSOCK_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
accept()
accept()
is used 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_t
integer that will indicate toaccept()
how large the sockaddr structure pointed to bycliaddr
is. Whenaccept()
returns, thesocklen_t
integer then indicates how many bytes of thecliaddr
structure were actually used.The function returns a socket corresponding to the accepted connection, or -1 if an error occurs.
Prototype
Blocking "vs." nonblocking
Berkeley sockets can operate in one of two modes: blocking or non-blocking. A "blocking" socket will not return control until it has sent (or received) all the data specified for the operation. This is true only in Linux systems. In other systems, such as FreeBSD, it is normal for a blocking socket not to send all the data. Always check the return value to find out how many bytes have been sent/received. It’s up to you to send the rest of the string [http://beej.us/guide/bgnet/] . It also 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
functions.ioctl ()Cleaning up
The system will not release the resources allocated by the
socket()
call until aclose()
call occurs. This is especially important if theconnect()
call fails and may be retried. Each call tosocket()
must have a matching call toclose()
in all possible execution paths. Includefor the close function. When an issue to the
close()
system call is made only the interface to the socket gets closed, not the socket itself. It is up to the kernel to close the socket. Sometimes, the socket may go into aTIME_WAIT
state, on the server side, for up to 4 minutes. [http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-4.html#ss4.2]See also
*
Computer network
*Internet socket
*Unix domain socket
*Winsock , the Berkeley sockets-basedapplication programming interface for networking onMicrosoft Windows References
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:2002Information about this standard and ongoing work on it is available from [http://www.opengroup.org/austin/ the Austin website] .
The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542.
External links
*Unix Manual Pages
** [http://www.die.net/doc/linux/man/man2/accept.2.html accept(2)]
** [http://www.die.net/doc/linux/man/man2/connect.2.html connect(2)]
* [http://beej.us/guide/bgnet/ Beej's Guide to Network Programming] - 2007
* [http://www.developerweb.net/forum/forumdisplay.php?f=70 UnixSocket FAQ]
* [http://xzdev.com/random_ip_cpp.html Get system IP list - C++ Example]
* [http://heather.cs.ucdavis.edu/~matloff/Networks/Intro/NetIntro.pdf quick TCP-IP NetIntro with C examples]
* [http://msdn2.microsoft.com/en-us/library/ms740096.aspx Porting Berkeley Socket programs to Winsock] - Microsoft's documentation.
* [http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq.html Programming UNIX Sockets in C - Frequently Asked Questions] - 1996
* [http://www.linuxjournal.com/article/2333 Linux network programming] - "Linux Journal ", 1998
Wikimedia Foundation. 2010.