Professional Documents
Culture Documents
Berkeley Sockets
Berkeley Sockets
Berkeley Sockets
Berkeley sockets
Berkeley sockets is an application programming interface (API) for Internet sockets and Unix domain sockets, used for
inter-process communication (IPC). It is commonly implemented as a library of linkable modules. It originated with the
4.2BSD Unix released in 1983.
A socket is an abstract representation (handle) for the local endpoint of a network communication path. The Berkeley
sockets API represents it as a file descriptor (file handle) in the Unix philosophy that provides a common interface for
input and output to streams of data.
Berkeley sockets evolved with little modification from a de facto standard into a component of the POSIX specification.
Therefore, the term POSIX sockets is essentially synonymous with Berkeley sockets. They are also known as BSD
sockets, acknowledging the first implementation in the Berkeley Software Distribution.
Contents
History and implementations
BSD and POSIX sockets
Alternatives
Header files
Socket API functions
socket
bind
listen
accept
connect
gethostbyname and gethostbyaddr
Protocol and address families
Raw sockets
Options for sockets
Blocking and non-blocking mode
Terminating sockets
Client-server example using TCP
Server
Client
Client-server example using UDP
Server
Client
Caveats
References
External links
https://en.wikipedia.org/wiki/Berkeley_sockets 1/12
4/2/2018 Berkeley sockets - Wikipedia
All modern operating systems implement a version of the Berkeley or POSIX socket interface. It became the standard
interface for connecting to the Internet. Even the Winsock implementation for MS Windows, developed by unaffiliated
developers, closely follows the standard.
The BSD sockets API is written in the C programming language. Most other programming languages provide similar
interfaces, typically written as a wrapper library based on the C API.[1]
Alternatives
The STREAMS-based Transport Layer Interface (TLI) API offers an alternative to the socket API. However, recent systems
that provide the TLI API also provide the Berkeley socket API.
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:
File Description
sys/socket.h Core socket functions and data structures.
AF_INET and AF_INET6 address families and their corresponding protocol families, PF_INET and
netinet/in.h
PF_INET6. These include standard IP addresses and TCP and UDP port numbers.
PF_UNIX and PF_LOCAL address family. Used for local communication between programs running on
sys/un.h
the same computer.
arpa/inet.h Functions for manipulating numeric IP addresses.
Functions for translating protocol names and host names into numeric addresses. Searches local data
netdb.h
as well as name services.
https://en.wikipedia.org/wiki/Berkeley_sockets 2/12
4/2/2018 Berkeley sockets - Wikipedia
socket
The function socket() creates an endpoint for communication and returns a file descriptor for the socket. socket()
takes three arguments:
domain, which specifies the protocol family of the created socket. For example:
https://en.wikipedia.org/wiki/Berkeley_sockets 3/12
4/2/2018 Berkeley sockets - Wikipedia
bind
bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not
assigned an address. This association with an address must be performed with the bind() system call before the socket can
accept connections to other hosts. bind() takes three arguments:
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:
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 the accept() function. The accept() function creates a new socket for
each connection and removes the connection from the listen queue. It takes 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 indicates how many bytes of the structure were actually used.
The accept() function returns the new socket descriptor for the accepted connection, or -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
The connect() system call 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 protocol, this establishes a connection. Certain types of protocols are
connectionless, most notably the User Datagram Protocol. 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.
https://en.wikipedia.org/wiki/Berkeley_sockets 4/12
4/2/2018 Berkeley sockets - Wikipedia
connect() returns an integer representing the error code: 0 represents success, while -1 represents an error. Historically,
in the 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.[3]
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 function are
getaddrinfo() and getnameinfo(), and are based on a new addrinfo data structure.
The following lists a sampling of protocol families (preceded by the standard symbolic identifier) defined in a modern
Linux or BSD implementation:
https://en.wikipedia.org/wiki/Berkeley_sockets 5/12
4/2/2018 Berkeley sockets - Wikipedia
A socket for communications using any family is created with the socket() function, by specifying the desired protocol
family (PF_-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 AF instead of PF. The AF-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 AF-constants were defined by the corresponding
protocol identifier, leaving the distinction between AF and PF constants as a technical argument of no practical
consequence. Indeed, much confusion exists in the proper usage of both forms.[4]
The POSIX.1—2008 specification doesn't specify any PF-constants, but only AF-constants[5]
Raw sockets
Raw sockets provide a simple interface that bypasses the processing by the host's TCP/IP stack. They permit
implementation of networking protocols in user space and aid in debugging of the protocol stack.[6] Raw sockets are used
by some services, such as ICMP, that operate at the Internet Layer of the TCP/IP model.
https://en.wikipedia.org/wiki/Berkeley_sockets 6/12
4/2/2018 Berkeley sockets - Wikipedia
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.[7] 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.
On the other hand, 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 conditions due to variances in
network link speed.
A socket is typically set to blocking or nonblocking mode using the fcntl() or ioctl() functions.
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 TIME_WAIT state, on the server side, for up to 4 minutes.[8]
On SVR4 systems use of close() may discard data. The use of shutdown() or SO_LINGER may be required on these
systems to guarantee delivery of all data.[9]
Server
Setting up a simple TCP server involves the following steps:
4. 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.
5. Communicating with the remote host, which can be done through send() and recv() or write() and read().
6. Eventually closing each socket that was opened, once it is no longer needed, using close().
The following program creates a TCP server on port number 1100:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
struct sockaddr_in sa;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (SocketFD == -1) {
perror("cannot create socket");
exit(EXIT_FAILURE);
}
sa.sin_family = AF_INET;
sa.sin_port = htons(1100);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
for (;;) {
int ConnectFD = accept(SocketFD, NULL, NULL);
if (0 > ConnectFD) {
perror("accept failed");
close(SocketFD);
exit(EXIT_FAILURE);
}
close(SocketFD);
return EXIT_SUCCESS;
}
https://en.wikipedia.org/wiki/Berkeley_sockets 8/12
4/2/2018 Berkeley sockets - Wikipedia
Client
Programming a TCP client application involves the following steps:
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main(void)
{
struct sockaddr_in sa;
int res;
int SocketFD;
sa.sin_family = AF_INET;
sa.sin_port = htons(1100);
res = inet_pton(AF_INET, "192.168.1.3", &sa.sin_addr);
shutdown(SocketFD, SHUT_RDWR);
close(SocketFD);
return EXIT_SUCCESS;
}
UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of
TCP ports.
https://en.wikipedia.org/wiki/Berkeley_sockets 9/12
4/2/2018 Berkeley sockets - Wikipedia
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 using recvfrom().
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h> /* for close() for socket */
#include <stdlib.h>
int main(void)
{
int sock;
struct sockaddr_in sa;
char buffer[1024];
ssize_t recsize;
socklen_t fromlen;
for (;;) {
recsize = recvfrom(sock, (void*)buffer, sizeof buffer, 0, (struct sockaddr*)&sa, &fromlen);
if (recsize < 0) {
fprintf(stderr, "%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("recsize: %d\n ", (int)recsize);
sleep(1);
printf("datagram: %.*s\n", (int)recsize, buffer);
}
}
Client
A simple client program for sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 and port
number 7654 might look like this:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(void)
{
int sock;
struct sockaddr_in sa;
int bytes_sent;
char buffer[200];
https://en.wikipedia.org/wiki/Berkeley_sockets 10/12
4/2/2018 Berkeley sockets - Wikipedia
/* IPv4 adresses is a uint32_t, convert a string representation of the octets to the appropriate value */
sa.sin_addr.s_addr = inet_addr("127.0.0.1");
/* sockets are unsigned shorts, htons(x) ensures x is in network byte order, set the port to 7654 */
sa.sin_port = htons(7654);
In this code, buffer is a pointer to the data to be sent, and buffer_length specifies the size of the data.
Caveats
For TCP connections, the operating system may have to retransmit the data given to it with a write() call. However, the
user space program is free to delete the data buffer passed to write() after write() returns. This implies that the
operating system must make a copy of the data which can lead to a considerable CPU load in high
throughput/performance applications. Other APIs, such as those supporting RDMA require that the data buffer is not
released until the acknowledgement from the remote end has been received and thus make it possible to have zero
memory copy operations.
References
1. E. g. in the Ruby programming language ruby-doc::Socket (http://www.ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/So
cket.html)
2. "— POSIX.1-2008 specification" (http://www.opengroup.org/onlinepubs/9699919799/functions/contents.html).
Opengroup.org. Retrieved 2012-07-26.
3. 2013, Stevens & Rago 607.
4. UNIX Network Programming Volume 1, Third Edition: The Sockets Networking API, W. Richard Stevens, Bill Fenner,
Andrew M. Rudoff, Addison Wesley, 2003.
5. "The Open Group Base Specifications Issue 7" (http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_soc
ket.h.html). Pubs.opengroup.org. Retrieved 2012-07-26.
6. https://msdn.microsoft.com/en-us/library/windows/desktop/ms740548(v=vs.85).aspx
7. "Beej's Guide to Network Programming" (http://beej.us/guide/bgnet/). Beej.us. 2007-05-05. Retrieved 2012-07-26.
8. "terminating sockets" (http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-faq-4.html#
ss4.2). Softlab.ntua.gr. Retrieved 2012-07-26.
https://en.wikipedia.org/wiki/Berkeley_sockets 11/12
4/2/2018 Berkeley sockets - Wikipedia
9. "ntua.gr - Programming UNIX Sockets in C - Frequently Asked Questions: Questions regarding both Clients and
Servers (TCP/SOCK_STREAM)" (http://www.softlab.ntua.gr/facilities/documentation/unix/unix-socket-faq/unix-socket-
faq-2.html#time_wait). Softlab.ntua.gr. Retrieved 2012-07-26.
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:2002
Information about this standard and ongoing work on it is available from the Austin website (http://www.opengroup.org/
austin/).
The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542.
W. Richard, Stevens; Stephen A., Rago (May 24, 2013). Advanced Programming in the UNIX Environment (http://ww
w.kohala.com/start/apue.html) (Third ed.). Addison-Wesley Professional. ISBN 978-0321637734. Retrieved
27 February 2015.
External links
Unix Manual Pages
accept(2) (http://www.die.net/doc/linux/man/man2/accept.2.html)
connect(2) (http://www.die.net/doc/linux/man/man2/connect.2.html)
UNIX Programmer's Supplementary Documents (PSD: 20-1) (http://docs.freebsd.org/44doc/psd/20.ipctut/paper.pdf)
Beej's Guide to Network Programming (http://beej.us/guide/bgnet/) - 2007
UnixSocket FAQ (http://www.developerweb.net/forum/forumdisplay.php?f=70)
quick TCP-IP NetIntro with C examples (http://heather.cs.ucdavis.edu/~matloff/Networks/Intro/NetIntro.pdf)
Porting Berkeley Socket programs to Winsock (http://msdn2.microsoft.com/en-us/library/ms740096.aspx) - Microsoft's
documentation.
Programming UNIX Sockets in C - Frequently Asked Questions (http://www.softlab.ntua.gr/facilities/documentation/un
ix/unix-socket-faq/unix-socket-faq.html) - 1996
Linux network programming (http://www.linuxjournal.com/article/2333) - Linux Journal, 1998
This article is based on material taken from the Free On-line Dictionary of Computing prior to 1 November 2008 and incorporated under the
"relicensing" terms of the GFDL, version 1.3 or later.
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this
site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia
Foundation, Inc., a non-profit organization.
https://en.wikipedia.org/wiki/Berkeley_sockets 12/12