Use
The use of the term socket in software is analogous to the function of an electrical female connector, a device in hardware for communication between nodes interconnected with an electrical cable. Similarly, the term port refers to external physical endpoints at a node or device.
The application programming interface (API) for the network protocol stack creates a handle for each socket created by an application, commonly referred to as a socket descriptor. In Unix-like operating systems, this descriptor is a type of file descriptor. It is stored by the application process for use with every read and write operation on the communication channel.
At the time of creation with the API, a network socket is bound to the combination of a type of network protocol to be used for transmissions, a network address of the host, and a port number. Ports are numbered resources that represent another type of software structure of the node. They are used as service types, and, once created by a process, serve as an externally (from the network) addressable location component, so that other hosts may establish connections.
Network sockets may be dedicated for persistent connections for communication between two nodes, or they may participate in connectionless and multicast communications.
In practice, due to the proliferation of the TCP/IP protocols in use on the Internet, the term network socket usually refers to use with the Internet Protocol (IP). It is therefore often also called Internet socket.
Socket addresses
An application can communicate with a remote process by exchanging data with TCP/IP by knowing the combination of protocol type, IP address, and port number. This combination is often known as a socket address. It is the network-facing access handle to the network socket. The remote process establishes a network socket in its own instance of the protocol stack and uses the networking API to connect to the application, presenting its own socket address for use by the application.
Implementation
A protocol stack, usually provided by the operating system (rather than as a separate library, for instance), is a set of services that allows processes to communicate over a network using the protocols that the stack implements. The operating system forwards the payload of incoming IP packets to the corresponding application by extracting the socket address information from the IP and transport protocol headers and stripping the headers from the application data.
The application programming interface (API) that programs use to communicate with the protocol stack, using network sockets, is called a socket API. Development of application programs that utilize this API is called socket programming or network programming. Internet socket APIs are usually based on the Berkeley sockets standard. In the Berkeley sockets standard, sockets are a form of file descriptor, due to the Unix philosophy that "everything is a file", and the analogies between sockets and files. Both have functions to read, write, open, and close. In practice, the differences strain the analogy, and different interfaces (send and receive) are used on a socket. In inter-process communication, each end generally has its own socket.
In the standard Internet protocols TCP and UDP, a socket address is the combination of an IP address and a port number, much like one end of a telephone connection is the combination of a phone number and a particular extension. Sockets need not have a source address, for example, for only sending data, but if a program a socket to a source address, the socket can be used to receive data sent to that address. Based on this address, Internet sockets deliver incoming to the appropriate application .
Definition
The distinctions between a socket (internal representation), socket descriptor (abstract identifier), and socket address (public address) are subtle, and these are not always distinguished in everyday usage. Further, specific definitions of a socket differ between authors. In IETF Request for Comments, Internet Standards, in many textbooks, as well as in this article, the term socket refers to an entity that is uniquely identified by the socket number. In other textbooks,1 the term socket refers to a local socket address, i.e., a "combination of an IP address and a port number". In the original definition of socket given in RFC 147,2 as it was related to the ARPA network in 1971, "the socket is specified as a 32-bit number with even sockets identifying receiving sockets and odd sockets identifying sending sockets." Today, however, socket communications are bidirectional.
Within the operating system and the application that created a socket, a socket is referred to by a unique integer value called a socket descriptor.
Example
This example in Java, modeled according to the Berkeley socket interface, sends the string "Hello, world!" via TCP to port 80 of the host with address 203.0.113.0. It illustrates the creation of a socket, connecting it to the remote host, sending the string, and finally closing the socket:
package org.wikipedia.examples;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
public class Main {
public static void main(String[] args) {
InetAddress address = InetAddress.getByName("203.0.113.0");
// IP = 203.0.113.0, port = 80
// the Socket is automatically closed at the end of the try block
// java.net.Socket uses TCP, while java.net.DatagramSocket uses UDP
try (Socket socket = new Socket(address, 80)) {
// writes to the output stream of the socket, with automatic flushing enabled
PrintWriter socketOut = new PrintWriter(socket.getOutputStream(), true);
socketOut.println("Hello, world!");
} catch (SocketException e) {
System.out.printf("An error occurred while accessing the socket: %s%n", e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.out.printf("An error occurred while writing to socket: %s%n", e.getMessage());
e.printStackTrace();
}
}
}
The traditional Berkeley sockets usage in C would look like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
char message[] = "Hello, World!";
// Create socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
fprintf(stderr, "Failed to create socket!\n");
return 1;
}
// Set server address
struct sockaddr_in server_addr = {
.sin_family = AF_INET, // Address family
.sin_port = htons(80), // Port number (converted to network byte order)
.sin_addr.s_addr = inet_addr("203.0.113.0"), // IP address
};
// Connect to server
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
fprintf(stderr, "Connection failed!\n");
return 1;
}
// Send message
send(sockfd, message, strlen(message), 0);
printf("Message sent!\n");
// Close socket
close(sockfd);
return 0;
}
Types
Several types of internet socket are available:
- Datagram sockets
- Connectionless sockets, which use User Datagram Protocol (UDP).4 Each packet sent or received on a datagram socket is individually addressed and routed. Order and reliability are not guaranteed with datagram sockets, so multiple packets sent from one machine or process to another may arrive in any order or might not arrive at all. Special configuration may be required to send broadcasts on a datagram socket.5 In order to receive broadcast packets, a datagram socket should not be bound to a specific address, though in some implementations, broadcast packets may also be received when a datagram socket is bound to a specific address.6
Socket states in the client-server model
Computer processes that provide application services are referred to as servers, and create sockets on startup that are in the listening state. These sockets are waiting for initiatives from client programs.
A TCP server may serve several clients concurrently by creating a unique dedicated socket for each client connection in a new child process or processing thread for each client. These are in the established state when a socket-to-socket virtual connection or virtual circuit (VC), also known as a TCP session, is established with the remote socket, providing a duplex byte stream.
A server may create several concurrently established TCP sockets with the same local port number and local IP address, each mapped to its own server-child process, serving its own client process. They are treated as different sockets by the operating system since the remote socket address (the client IP address or port number) is different; i.e., since they have different socket pair tuples.
UDP sockets do not have an established state, because the protocol is connectionless. A UDP server process handles incoming datagrams from all remote clients sequentially through the same socket. UDP sockets are not identified by the remote address, but only by the local address, although each message has an associated remote address that can be retrieved from each datagram with the networking application programming interface (API).
Socket pairs
Local and remote sockets communicating over TCP are called socket pairs. Each socket pair is described by a unique 4-tuple consisting of source and destination IP addresses and port numbers, i.e. of local and remote socket addresses.1112 As discussed above, in the TCP case, a socket pair is associated on each end of the connection with a unique 4-tuple.
History
The term socket dates to the publication of RFC 147 in 1971, when it was used in the ARPANET. Most modern implementations of sockets are based on Berkeley sockets (1983), and other stacks such as Winsock (1991). The Berkeley sockets API in the Berkeley Software Distribution (BSD) originated with the 4.2BSD Unix operating system as an API. 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.
In c. 1987, AT&T introduced the STREAMS-based Transport Layer Interface (TLI) in UNIX System V Release 3 (SVR3).13 and continued into Release 4 (SVR4).14
Other early implementations were written for TOPS-20,15 MVS,15 VM,15 IBM-DOS (PCIP).15
References
- 1Cisco Networking Academy Program, CCNA 1 and 2 Companion Guide Revised Third Edition, P.480, ISBN 1-58713-150-1
- 2RFC 147
- 3Jack Wallen (2019-01-22). "An Introduction to the ss Command". Archived from the original on 2019-08-05. Retrieved 2019-08-05.
- 4V. S. Bagad, I. A. Dhotre (2008), Computer Networks (5th revised edition, 2010 ed.), Technical Publications Pune, p. 52
- 5SO_BROADCAST, Microsoft, retrieved 2019-12-12
- 6Class DatagramSocket, Oracle, archived from the original on 2019-12-12, retrieved 2019-12-12
- 7Ian Griffiths for IanG on Tap. 12 August 2004. 2021-02-09 at the
Further reading
- Jones, Anthony; Ohlund, Jim (2002). Network Programming for Microsoft Windows. Microsoft Press. ISBN 0-7356-1579-9.