Network socket

A socket ( abgel of Engl. Pedestal or connector, socket ) is a software module that allows to connect to a computer program with a computer network and can exchange data with other computers. Sockets are also used to send data between processes on the same computer ( interprocess communication). The communication socket is bi-directional in the control, that is, via the socket data is both received and transmitted.

  • 2.1 Stream Sockets
  • 2.2 Datagram Sockets
  • 3.1 alternatives
  • 6.1 BSD sockets API
  • 6.2 C
  • 6.3 Java
  • 6.4 Haskell 6.4.1 Simple Server
  • 6.4.2 Simple Client


Sockets are a platform-independent, standardized interface ( API) between the network protocol implementation of the operating system and the actual application software. A computer program requests a socket by the operating system. The operating system has the task of managing all used sockets and the associated connection information.

Internet Sockets

Internet Sockets allow communication using certain communication protocols. Generally, one can distinguish between stream sockets and datagram sockets: stream sockets communicate over a character stream; Datagram sockets through individual messages. In network communications Stream sockets use TCP usually, Datagram Sockets usually UDP. TCP is reliable, the order and delivery of packages are guaranteed ( principle: all or nothing ). UDP is more efficient and flexible for certain tasks, often faster (in time) - however, order and delivery of the packets are not guaranteed ( still are duplicates possible).

While stream sockets and datagram sockets the TCP or UDP header of a data packet normally hide and automatically put, raw sockets can ( Raw: raw) to create their own TCP and UDP headers. Raw sockets are most used in network- related applications, such as for routers, packet sniffers or packet injection.

A socket is usually the connection point to a particular remote program, represented by its address information ( eg IP address and port number). The socket itself is of course also assigned its own address information. An Internet socket address family AF_INET is represented by the following information:

  • Sin_family, ie the associated address family of the network ( eg AF_INET address family = Internet address)
  • The identification number of Local-Host/seiner 32- bit IP address
  • The port number of Local-Host/16 bit

This information is, however, dependent on the protocol used. Typically, at the address information on the Internet about the IP address and port. For UNIX domain sockets (see below), the identification of a file path name and the address family AF_UNIX.

A server can either wait for requests from a specific address ( and binds from the outset to this address ) or it waits for all addresses his computer to requests. There is, in some protocols, a so-called wild - address, wherein the one or more parts of the address information is not specific. In the example of TCP / IP and UDP / IP only the port number is relevant to a wildcard address, that is, it is a special (invalid ) IP address specified to indicate that connections on all IP addresses accepted should be. In Linux, this wildcard address is ( symbolic constant INADDR_ANY ).

When the server receives a request from a client that is in the listening ( "listening " ) server socket of related ( " connected" ) server socket derived: The original server socket remains intact and continues to wait for new connections, while a new, directed to the specific client socket is opened, which is used only for communication with said one client. This remains in effect until the connection to the client from one of the two sides is terminated. This derivation can be used to create a parallelized server architecture in which the server forks when inquiring and answering a child process the request itself.

That is, one with a client socket connected ( " connected" ) server socket exactly the same IP address and port number of bears ( "listen " ) server socket as the listening. The distinction of simultaneous client connections to the same server, therefore takes place by the pair of the server socket and client socket. This pair must at all times be unique to each of the communication partners involved. As an example, an HTTP server where the listening on port 80. The compounds of the server to various clients leads to the following unique "connected " pairs of sockets on the server machine:

( : 80; : ), ( : 80; : ), ( : 80; < Client_B IP >: ) etc..

End of the socket communication

Stream sockets

On the client side:

Server - side:

Datagram Sockets

On the client side:

Server - side:

Sockets and interprocess communication

Unix operating systems use for local inter-process communication called POSIX Local Inter-Process Communication Sockets (also IPC sockets, of "inter- process communication sockets ", or Unix domain sockets ). Again, there is datagram and stream sockets; because communication but takes place in the kernel behave Stream and Datagram Sockets very similar ( for example, there is here also with Datagram Sockets no risk of data loss). A Unix domain socket is represented as a special file in the file system, which can be regarded as analogous to the pair of IP address and port on AF_INET sockets. Unix domain sockets are for the IPC compared to "normal " sockets that use the loopback interface, the advantage of a much higher throughput.


Alternatives to sockets in the inter-process communication are pipes or shared memory.


Under Unix follows the input / output handling (I / O) the so-called Open -Read -Write -Close algorithm:

As has network support in Unix systems integrated, they wanted to make this similar to the communication ORWC algorithm. The result was 1983, the Berkeley Sockets API for BSD Unix.

Use in different operating systems

Unix and Unix- like operating systems (such as Linux ) use very often BSD sockets for network communication. For local interprocess communication they use so-called Unix domain sockets ( which are part of the POSIX standard ): These processes can communicate in a simple manner with each other. For the programmer, the communication looks almost exactly as he would read and write, it will be the same commands used in a normal file.

Windows uses a BSD Sockets modeled so-called Windows Sockets API ( Winsock).

For security reasons, the ports are up to and including 1023 for unprivileged programs usually locked, to prevent reserved standard services such as HTTP, FTP, POP3, SMTP, etc. can be hijacked by users.

Socket programming

BSD sockets API

Both Unix Sockets and Windows sockets based on the BSD sockets API published in 1983. Important features of this API are summarized here for the following programming examples:

  • Socket () Creates a new socket allocated for this specific type and system resources. To identify the function returns a unique number of the integer type.
  • Bind ( ) Binds the socket to a socket address information, usually to an IP address and port. This is typically used on server side.
  • Listen () Puts a bound STREAM (TCP / IP) socket in a listening mode. It is used on the server side.
  • Connect ( ) If known, the address information (eg IP address and port) of another socket. Assigns the socket to an available local port. In the case of stream sockets, a new TCP / IP connection is attempted to be established. It is used on the client side.
  • Accept ( ) Accepts an incoming test ( request) to build on success and generated a new socket associated with the address pair of connecting a new TCP / IP connection to a remote client. This newly created socket is returned by the function. It is used on the server side.
  • Send () and recv () or write () and read ( ) or sendto () and recvfrom ( ) Writes / reads data to / from socket ( s ). Note: A single function call to recv ( ) is not guaranteed to receive all the data sent by the transmitter via send ( ), especially not with STREAM sockets.
  • Close () Causes the operating system to release all allocated for the socket resources. Is a TCP / IP socket, the connection is terminated.


The derived POSIX Sockets API of Linux is written in C. An example of a TCP connection of a client to a server:

Int sockfd = socket ( AF_INET, SOCK_STREAM, 0); / / Create Socket   struct sockaddr_in srv;   memset ( & srv, 0, sizeof (struct sockaddr_in ) );   srv.sin_family = AF_INET; inet_pton ( AF_INET, " ", & srv.sin_addr ); / / Write the IP address of the server in the sockaddr_in structure srv.sin_port = htons ( 1234); / / Write Port sin_port in network byte order ( big-endian ) in the field   connect ( sockfd, (struct sockaddr * ) & srv, sizeof ( struct sockaddr_in ) ); / / Connect   / / From now on can be read from the socket and write to the socket using write () and read ().   [ ...] / / Data exchange   shutdown ( sockfd, SHUT_WR ); / / Send an EOF byte, so that the server during the next read () return value 0 gets                            can / and exit / link   close ( sockfd ); Java

Java as a platform- independent programming language supported in the package directly socket programming. Showing the operating system independence of the socket concept. The implementation of the sockets for the different platforms (Linux, Windows, Special Systems ) takes place in the class library to the virtual machine.

The classes for socket programming are Socket and ServerSocket. The following short example illustrates the use of:

ServerSocket server socket = new ServerSocket (port ); / / Create a server socket with a specific port number   while ( true) {     Socket socket = client serverSocket.accept (); / wait / to requests     InputStream input = clientSocket.getInputStream (); / / Open InputStream object     byte [] data = new byte; / / Declare data buffer (create)     int numBytes = 0; / / Variable for the number of bytes actually read     numBytes = ( data); / / Read data     / *** Read data process *** /     clientSocket.close (); / / Close connection   } There is also the opportunity to talk about the sockets NewIO ( nio ) library in the current version of Java. The code is a bit more complicated, but can be executed faster. The multiplexing of several sockets is done through a so-called Selector (similar to the Unix system call select).


The purely functional programming language Haskell provides a platform-independent way to use a socket through the module Network. The following example contains the complete code for a very simple server, and a corresponding client. The client accepts text lines meet them from the standard input and sends it over the network socket to the server. This in turn gives the lines of text to the standard output.

Single server

Module Main where   import Control.Concurrent import Control.Monad import System.IO import Network   main :: IO ( ) main = do $ withSocketsDo           theSocket <- ListenOn ( PortNumber 2048)           forever $ acceptConnectionAndFork theSocket echoserver   type message handler = (handle, string, Port Number) - > IO ( )   acceptConnectionAndFork :: Socket -> Message Handler -> IO ( ) acceptConnectionAndFork theSocket handler = do    connection < - accept theSocket    forkIO $ handler connection    return ()   echoserver :: Message Handler echoserver (handle, hostname, port number) = do    putStrLn $ " (" hostname " :" show portNumber "): Open"    c < - hGetContents handle    mapM_ putStrLn [" (" hostname " :" show portNumber "): msg " show l | l < -lines c]    putStrLn $ " (" hostname " :" show portNumber "): Close" simple client

Module Main where   import Network import System.IO import Control.Concurrent   main :: IO ( ) main = do $ withSocketsDo           handle < - ConnectTo "localhost" ( PortNumber 2048)           input < - getContents           sequence_ [ do                        hPutStrLn handle l                        hFlush handle |                     l < -lines input]           hClose handle Ruby

In Ruby, the standard library socket also a platform independent programming interface for TCP sockets available.

A very simple server ( multithreaded ), which sends a text to the client:

Require 'socket '   port = 2048 server = (port ) loop do    client = server.accept    Thread.start (client ) do | c |      c.puts 'Hello! '      c.close    end end Web Links

  • Socket programming in Python ( s)
  • Realistic example of the construction of a socket server with safe completion in Haskell
  • GNU info- Page via sockets (s)
  • Echo server based on the Linux Sockets API and TCP sockets
  • Unix
  • Library (programming)
  • Computer Networks