Berkeley socketsA Berkeley (BSD) socket is an application programming interface (API) for Internet domain 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 operating system, which was 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 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. The term POSIX sockets is essentially synonymous with Berkeley sockets, but they are also known as BSD sockets, acknowledging the first implementation in the Berkeley Software Distribution. History and implementationsBerkeley sockets originated with the 4.2BSD Unix operating system, released in 1983, as a programming interface. Not until 1989, however, could the University of California, Berkeley release versions of the operating system and networking library free from the licensing constraints of AT&T Corporation's proprietary Unix. All modern operating systems implement a version of the Berkeley socket interface. It became the standard interface for applications running in the Internet. Even the Winsock implementation for MS Windows, created 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] BSD and POSIX socketsAs the Berkeley socket API evolved and ultimately yielded the POSIX socket API,[2] certain functions were deprecated or removed and replaced by others. The POSIX API is also designed to be reentrant and supports IPv6.
AlternativesThe STREAMS-based Transport Layer Interface (TLI) API offers an alternative to the socket API. Many systems that provide the TLI API also provide the Berkeley socket API. Non-Unix systems often expose the Berkeley socket API with a translation layer to a native networking API. Plan 9[3] and Genode[4] use file-system APIs with control files rather than file-descriptors. Header filesThe Berkeley socket interface is defined in several header files. The names and content of these files differ slightly between implementations. In general, they include:
Socket API functions![]() The Berkeley socket API typically provides the following functions:
socketThe function
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor. bind
listenAfter 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:
Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is returned. acceptWhen an application is listening for stream-oriented connections from other hosts, it is notified of such events (cf.
Datagram sockets do not require processing by connect
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,
gethostbyname and gethostbyaddrThe functions
The functions return These functions are not strictly a component of the BSD socket API, but are often used in conjunction with the API functions for looking up a host. 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 functions are getaddrinfo() and getnameinfo(), and are based on a new This pair of functions appeared at the same time as the BSD socket API proper in 4.2BSD (1983),[7] the same year DNS was first created. Early versions did not query DNS and only performed /etc/hosts lookup. The 4.3BSD (1984) version added DNS in a crude way. The current implementation using Name Service Switch derives Solaris and later NetBSD 1.4 (1999).[8] Initially defined for NIS+, NSS makes DNS only one of the many options for lookup by these functions and its use can be disabled even today.[9] Protocol and address familiesThe Berkeley socket API is a general interface for networking and interprocess communication and supports the use of various network protocols and address architectures. The following lists a sampling of protocol families (preceded by the standard symbolic identifier) defined in a modern Linux or BSD implementation:
A socket for communications is created with the 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.[11] The POSIX.1—2008 specification doesn't specify any PF-constants, but only AF-constants[12] Raw socketsRaw 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.[13] Raw sockets are used by some services, such as ICMP, that operate at the Internet Layer of the TCP/IP model. Blocking and non-blocking modeBerkeley sockets can operate in one of two modes: blocking or non-blocking. 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.[14] 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. 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.[citation needed] A socket is typically set to blocking or non-blocking mode using the functions fcntl and ioctl. Terminating socketsThe 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.[15] On SVR4 systems, use of Client-server example using TCPThe Transmission Control Protocol (TCP) is a connection-oriented protocol that provides a variety of error correction and performance features for transmission of byte streams. A process creates a TCP socket by calling the ServerEstablishing a TCP server involves the following basic steps:
The following program creates a TCP server listening on port number 1100: #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.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");
return EXIT_FAILURE;
}
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(1100);
sa.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(SocketFD, (struct sockaddr*)&sa, sizeof sa) == -1) {
perror("bind failed");
close(SocketFD);
return EXIT_FAILURE;
}
if (listen(SocketFD, 10) == -1) {
perror("listen failed");
close(SocketFD);
return EXIT_FAILURE;
}
while (true) {
int ConnectFD = accept(SocketFD, NULL, NULL);
if (ConnectFD == -1) {
perror("accept failed");
close(SocketFD);
return EXIT_FAILURE;
}
/* perform read write operations ...
read(ConnectFD, buff, size)
*/
if (shutdown(ConnectFD, SHUT_RDWR) == -1) {
perror("shutdown failed");
close(ConnectFD);
close(SocketFD);
return EXIT_FAILURE;
}
close(ConnectFD);
}
close(SocketFD);
return EXIT_SUCCESS;
}
ClientProgramming a TCP client application involves the following steps:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
struct sockaddr_in sa;
int res;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (SocketFD == -1) {
perror("cannot create socket");
return EXIT_FAILURE;
}
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(1100);
res = inet_pton(AF_INET, "192.168.1.3", &sa.sin_addr);
if (connect(SocketFD, (struct sockaddr*)&sa, sizeof sa) == -1) {
perror("connect failed");
close(SocketFD);
return EXIT_FAILURE;
}
/* perform read write operations ... */
close(SocketFD);
return EXIT_SUCCESS;
}
Client-server example using UDPThe User Datagram Protocol (UDP) is a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. Because of this minimal design, UDP has considerably less overhead than TCP. Being connectionless means that there is no concept of a stream or permanent connection between two hosts. Such data are referred to as datagrams (datagram sockets). UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports. ServerAn application may set up a UDP server on port number 7654 as follows. The programs contains an infinite loop that receives UDP datagrams with function #include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
int sock;
struct sockaddr_in sa;
char buffer[1024];
ssize_t recsize;
socklen_t fromlen;
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons(7654);
fromlen = sizeof sa;
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (bind(sock, (struct sockaddr *)&sa, sizeof sa) == -1) {
perror("error bind failed");
close(sock);
return EXIT_FAILURE;
}
while (true) {
recsize = recvfrom(sock, (void*)buffer, sizeof buffer, 0, (struct sockaddr*)&sa, &fromlen);
if (recsize < 0) {
fprintf(stderr, "%s\n", strerror(errno));
return EXIT_FAILURE;
}
printf("recsize: %d\n ", (int)recsize);
sleep(1);
printf("datagram: %.*s\n", (int)recsize, buffer);
}
}
ClientThe following is a client program for sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 at port number 7654. #include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
int main(void) {
int sock;
struct sockaddr_in sa;
int bytes_sent;
char buffer[200];
strcpy(buffer, "hello world!");
// create an Internet, datagram, socket using UDP
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == -1) {
/* if socket failed to initialize, exit */
printf("Error Creating Socket");
return EXIT_FAILURE;
}
// Zero out socket address
memset(&sa, 0, sizeof sa);
// The address is IPv4
sa.sin_family = AF_INET;
// IPv4 addresses 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);
bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, sizeof sa);
if (bytes_sent < 0) {
printf("Error sending packet: %s\n", strerror(errno));
return EXIT_FAILURE;
}
close(sock); // close the socket
return 0;
}
In this code, References
The de jure standard definition of the Sockets interface is contained in the POSIX standard, known as:
Information about this standard and ongoing work on it is available from the Austin website. The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542.
External links |