Berkeley sockets 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 Network 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 Standard 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.
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 Microsoft 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.E. g. in the Ruby programming language class Socket
| Conversion from text address to packed address | inet_aton | inet_pton |
| Conversion from packed address to text address | inet_ntoa | inet_ntop |
| Forward lookup for host name/service | gethostbyname, gethostbyaddr, getservbyname, getservbyport | getaddrinfo |
| Reverse lookup for host name/service | gethostbyaddr, getservbyport | getnameinfo |
Non-Unix systems often expose the Berkeley socket API with a translation layer to a native networking API. Plan 9 and Genode use file-system APIs with control files rather than file-descriptors.
| Functions for manipulating numeric IP addresses. |
| and address families and their corresponding protocol families, and . These include standard IP addresses and TCP and UDP port numbers. |
| Functions for translating protocol names and host names into numeric addresses. Searches local data as well as name services. |
| Core socket functions and data structures. |
| and address family. Used for local communication between programs running on the same computer. |
The function returns if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor.
associates a socket with an address. When a socket is created with , it is only given a protocol family, but not assigned an address. This association must be performed before the socket can accept connections from other hosts. The function has three arguments:
returns on success and if an error occurs.
returns the new socket descriptor for the accepted connection, or the value if an error occurs. All further communication with the remote host now occurs via this new socket.
Datagram sockets do not require processing by since the receiver may immediately respond to the request using the listening socket.
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, defines the remote address for sending and receiving data, allowing the use of functions such as and . In these cases, the connect function prevents reception of datagrams from other sources.
returns an integer representing the error code: represents success, while represents an error. Historically, in BSD-derived systems, the state of a socket descriptor is undefined if the call to 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 , in the case the call to fails.
The functions return in case of error, in which case the external integer may be checked to see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid h_errno is returned.
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 are based on a new data structure.POSIX.1-2004
This pair of functions appeared at the same time as the BSD socket API proper in 4.2BSD (1983), 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). 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.
The following lists a sampling of protocol families (preceded by the standard symbolic identifier) defined in a modern Linux or BSD implementation:
| AppleTalk | |
| Asynchronous Transfer Mode Permanent Virtual Circuits | |
| Asynchronous Transfer Mode Switched Virtual Circuits | |
| Amateur Radio AX.25 | |
| Controller Area Network | |
| Bluetooth sockets | |
| Multiprotocol bridge | |
| Reserved for DECnet project | |
| Acorn Econet | |
| Internet Protocol version 4 | |
| Internet Protocol version 6 | |
| Novell's Internetwork Packet Exchange | |
| IrDA sockets | |
| key management API | |
| Local to host (pipes and file-domain) | |
| Amateur radio NET/ROM (related to AX.25) | |
| Reserved for 802.2LLC project | |
| Security callback pseudo AF | |
| routing API | |
| Packet capture sockets | |
| PPPoX sockets | |
| Linux Systems Network Architecture (SNA) Project | |
| Sangoma Wanpipe API sockets |
A socket for communications is created with the function, by specifying the desired protocol family ( 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 instead of . The 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 constants were defined by the corresponding protocol identifier, leaving the distinction between and constants as a technical argument of no practical consequence. Indeed, much confusion exists in the proper usage of both forms. UNIX Network Programming Volume 1, Third Edition: The Sockets Networking API, W. Richard Stevens, Bill Fenner, Andrew M. Rudoff, Addison Wesley, 2003.
The POSIX.1-2008 specification does not specify any constants, but only constants.
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. 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 due to variances in network link speed.
A socket is typically set to blocking or non-blocking mode using the functions fcntl and ioctl.
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 state, on the server side, for up to 4 minutes.
On SVR4 systems, use of may discard data. The use of or SO_LINGER may be required on these systems to guarantee delivery of all data.
The following program creates a TCP server listening on port number 1100:
int main(void) {
int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1) {
fprintf(stderr, "Failed to create socket!\n");
return EXIT_FAILURE;
}
struct sockaddr_in sa = {
.sin_family = AF_INET,
.sin_port = htons(1100),
.sin_addr.s_addr = htonl(INADDR_ANY)
};
if (bind(sockfd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
fprintf(stderr, "Failed to bind socket!\n");
close(sockfd);
return EXIT_FAILURE;
}
if (listen(sockfd, 10) == -1) {
fprintf(stderr, "Failed to listen on socket!\n");
close(sockfd);
return EXIT_FAILURE;
}
while (true) {
int connfd = accept(sockfd, NULL, NULL);
if (connfd == -1) {
fprintf(stderr, "Failed to accept connection!\n");
close(sockfd);
return EXIT_FAILURE;
}
// perform read write operations...
// read(connfd, buff, size)
if (shutdown(connfd, SHUT_RDWR) == -1) {
fprintf(stderr, "Failed to shutdown connection!\n");
close(connfd);
close(sockfd);
return EXIT_FAILURE;
}
close(connfd);
}
close(sockfd);
return EXIT_SUCCESS;
}
int main(void) {
int sockfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sockfd == -1) {
fprintf(stderr, "Failed to create socket!\n");
return EXIT_FAILURE;
}
struct sockaddr_in sa = {
.sin_family = AF_INET,
.sin_port = htons(1100),
};
int res = inet_pton(AF_INET, "192.168.1.3", &sa.sin_addr);
if (connect(sockfd, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
fprintf(stderr, "Failed to establish connection!\n");
close(sockfd);
return EXIT_FAILURE;
}
// perform read write operations...
close(sockfd);
return EXIT_SUCCESS;
}
UDP address space, the space of UDP port numbers (in ISO terminology, the ), is completely disjoint from that of TCP ports.
int main(void) {
struct sockaddr_in sa = {
.sin_family = AF_INET,
.sin_addr.s_addr = htonl(INADDR_ANY),
.sin_port = htons(7654)
};
char buffer[1024];
ssize_t recsize;
socklen_t fromlen = sizeof(sa);
int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (bind(sock, (struct sockaddr*)&sa, sizeof(sa)) == -1) {
fprintf(stderr, "Failed to bind socket!\n");
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);
}
}
int main(void) {
struct sockaddr_in sa = {
// The address is IPv4
.sin_family = AF_INET,
// IPv4 addresses is a uint32_t, convert a string representation of the octets to the appropriate value
.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
.sin_port = htons(7654)
};
char buffer[200];
strcpy(buffer, "Hello, world!");
// Create an Internet, datagram socket using UDP
int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sock == -1) {
// If socket failed to initialize, exit
fprintf(stderr, "Failed to create socket!\n");
return EXIT_FAILURE;
}
// Send message using sendto()
int bytes_sent = sendto(sock, buffer, strlen(buffer), 0, (struct sockaddr*)&sa, sizeof(sa));
if (bytes_sent < 0) {
fprintf(stderr, "Error sending packet: %s\n", strerror(errno));
return EXIT_FAILURE;
}
close(sock); // close the socket
return 0;
}
In this code, is a pointer to the data to be sent, and specifies the size of the data.
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.
|
|