Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikipediaThe Free Encyclopedia
Search

Berkeley sockets

From Wikipedia, the free encyclopedia
Inter-process communication API

Berkeley sockets is anapplication programming interface (API) forInternet domain sockets andUnix domain sockets, used forinter-process communication (IPC). It is commonly implemented as alibrary of linkable modules. It originated with the4.2BSD Unix operating system, which was released in 1983.

Asocket is an abstract representation (handle) for the local endpoint of a network communication path. The Berkeley sockets API represents it as afile descriptor in theUnix philosophy that provides a common interface for input and output tostreams of data.

Berkeley sockets evolved with little modification from ade facto standard into a component of thePOSIX specification. The termPOSIX sockets is essentially synonymous withBerkeley sockets, but they are also known asBSD sockets, acknowledging the first implementation in theBerkeley Software Distribution.

History and implementations

[edit]

Berkeley sockets originated with the 4.2BSDUnixoperating system, released in 1983, as a programming interface. Not until 1989, however, could theUniversity of California, Berkeley release versions of the operating system and networking library free from the licensing constraints ofAT&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 theInternet. Even theWinsock implementation for MS Windows, created by unaffiliated developers, closely follows the standard.

The BSD sockets API is written in theC programming language. Most other programming languages provide similar interfaces, typically written as awrapper library based on the C API.[1]

BSD and POSIX sockets

[edit]

As 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 bereentrant and supports IPv6.

ActionBSDPOSIX
Conversion from text address to packed addressinet_atoninet_pton
Conversion from packed address to text addressinet_ntoainet_ntop
Forward lookup for host name/servicegethostbyname, gethostbyaddr, getservbyname, getservbyportgetaddrinfo
Reverse lookup for host name/servicegethostbyaddr, getservbyportgetnameinfo

Alternatives

[edit]

TheSTREAMS-basedTransport 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] andGenode[4] use file-system APIs with control files rather than file-descriptors.

Header files

[edit]

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:

FileDescription
<arpa/inet.h>Functions for manipulating numeric IP addresses.
<netinet/in.h>AF_INET andAF_INET6 address families and their corresponding protocol families,PF_INET andPF_INET6. These include standard IP addresses and TCP and UDP port numbers.
<netdb.h>Functions for translating protocol names and host names into numeric addresses. Searches local data as well as name services.
<sys/socket.h>Core socket functions and data structures.
<sys/un.h>PF_UNIX andPF_LOCAL address family. Used for local communication between programs running on the same computer.

Socket API functions

[edit]
Flow diagram of client-server transaction using sockets with the Transmission Control Protocol (TCP).

The Berkeley socket API typically provides the following functions:

  • socket() creates a new socket of a certain type, identified by an integer number, and allocates system resources to it.
  • bind() is typically used on the server side, and associates a socket with a socket address structure, i.e. a specified local IP address and a port number.
  • listen() is used on the server side, and causes a bound TCP socket to enter listening state.
  • connect() is used on the client side, and assigns a free local port number to a socket. In case of a TCP socket, it causes an attempt to establish a new TCP connection.
  • accept() is used on the server side. It accepts a received incoming attempt to create a new TCP connection from the remote client, and creates a new socket associated with the socket address pair of this connection.
  • send(),recv(),sendto(), andrecvfrom() are used for sending and receiving data. The standard functionswrite() andread() may also be used.
  • close() causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated.
  • gethostbyname() andgethostbyaddr() are used to resolve host names and addresses. IPv4 only.
  • getaddrinfo() andfreeaddrinfo() are used to resolve host names and addresses. IPv4, IPv6.
  • select() is used to suspend, waiting for one or more of a provided list of sockets to be ready to read, ready to write, or that have errors.
  • poll() is used to check on the state of a socket in a set of sockets. The set can be tested to see if any socket can be written to, read from or if an error occurred.
  • getsockopt() is used to retrieve the current value of a particular socket option for the specified socket.
  • setsockopt() is used to set a particular socket option for the specified socket.

socket

[edit]

The functionsocket() creates an endpoint for communication and returns afile descriptor for the socket. It uses three arguments:

  • domain, which specifies the protocol family of the created socket. For example:
    • PF_INET for network protocolIPv4 (IPv4-only)
    • PF_INET6 forIPv6 (and in some cases,backward compatible with IPv4)
    • PF_UNIX for local socket (using a special filesystem node)
  • type, one of:
    • SOCK_STREAM (reliable stream-oriented service orstream sockets)
    • SOCK_DGRAM (datagram service ordatagram sockets)
    • SOCK_SEQPACKET (reliable sequenced packet service)
    • SOCK_RAW (raw protocols atop the network layer)
  • protocol specifying the actual transport protocol to use. The most common areIPPROTO_TCP,IPPROTO_SCTP,IPPROTO_UDP,IPPROTO_DCCP. These protocols are specified in file<netinet/in.h>. The value0 may be used to select a default protocol from the selected domain and type.

The function returns-1 if an error occurred. Otherwise, it returns an integer representing the newly assigned descriptor.

bind

[edit]

bind() associates a socket with an address. When a socket is created withsocket(), 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:

  • sockfd, a descriptor representing the socket
  • my_addr, a pointer to asockaddr structure representing the address to bind to.
  • addrlen, a field of typesocklen_t specifying the size of thesockaddr structure.

bind() returns0 on success and-1 if an error occurs.

listen

[edit]

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:

  • sockfd, a valid socket descriptor.
  • backlog, an integer representing the number of pending connections that can be queued up at any one time. The operating system usually places a cap on this value.

Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is returned.

accept

[edit]

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 functionaccept(). It creates a new socket for each connection and removes the connection from the listening queue. The function has 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 asocklen_t location that specifies the size of the client address structure passed toaccept(). Whenaccept() returns, this location contains the size (in bytes) of the structure.

accept() returns the new socket descriptor for the accepted connection, or the value-1 if an error occurs. All further communication with the remote host now occurs via this new socket.

Datagram sockets do not require processing byaccept() since the receiver may immediately respond to the request using the listening socket.

connect

[edit]

connect() establishes a direct communication link to a specific remote host identified by its address via a socket, identified by its file descriptor.

When using aconnection-oriented protocol, this establishes a connection. Certain types of protocols are connectionless, most notably theUser Datagram Protocol. When used with connectionless protocols,connect defines the remote address for sending and receiving data, allowing the use of functions such assend andrecv. In these cases, the connect function prevents reception of datagrams from other sources.

connect() returns an integer representing the error code:0 represents success, while–1 represents an error. Historically, in BSD-derived systems, the state of a socket descriptor is undefined if the call toconnect fails (as it is specified in the Single Unix Specification), thus, portable applications should close the socket descriptor immediately and obtain a new descriptor withsocket(), in the case the call toconnect() fails.[5]

gethostbyname and gethostbyaddr

[edit]

The functionsgethostbyname() andgethostbyaddr() are used to resolve host names and addresses in thedomain name system or the local host's other resolver mechanisms (e.g.,/etc/hosts lookup). They return a pointer to an object of typestruct hostent, which describes anInternet Protocol host. The functions use the following arguments:

  • name specifies the name of the host.
  • addr specifies a pointer to astruct in_addr containing the address of the host.
  • len specifies the length, in bytes, ofaddr.
  • type specifies the address family type (e.g.,AF_INET) of the host address.

The functions returnNULL in case of error, in which case the external integerh_errno may be checked to see whether this is a temporary failure or an invalid or unknown host. Otherwise a validstruct hostent* 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 aregetaddrinfo() andgetnameinfo(), and are based on a new[[addrinfo]] data structure.[6]

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 usingName Service Switch derives Solaris and later NetBSD 1.4 (1999).[8] Initially defined forNIS+, 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 families

[edit]

The 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 modernLinux orBSD implementation:

IdentifierFunction or use
PF_APPLETALKAppleTalk
PF_ATMPVCAsynchronous Transfer Mode Permanent Virtual Circuits
PF_ATMSVCAsynchronous Transfer Mode Switched Virtual Circuits
PF_AX25Amateur RadioAX.25
PF_CANController Area Network
PF_BLUETOOTHBluetooth sockets
PF_BRIDGEMultiprotocolbridge
PF_DECnetReserved forDECnet project
PF_ECONETAcornEconet
PF_INETInternet Protocol version 4
PF_INET6Internet Protocol version 6
PF_IPXNovell'sInternetwork Packet Exchange
PF_IRDAIrDA sockets
PF_KEYPF_KEY key management API
PF_LOCAL,PF_UNIX,PF_FILELocal to host (pipes and file-domain)
PF_NETROMAmateur radio NET/ROM (related to AX.25)[10]
PF_NETBEUIReserved for 802.2LLC project
PF_SECURITYSecurity callback pseudo AF
PF_NETLINK,PF_ROUTErouting API
PF_PACKETPacket capture sockets
PF_PPPOXPPP over X sockets
PF_SNALinuxSystems Network Architecture (SNA) Project
PF_WANPIPESangoma Wanpipe API sockets

A socket for communications is created with thesocket() 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 prefixAF instead ofPF. TheAF-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 theAF-constants were defined by the corresponding protocol identifier, leaving the distinction betweenAF andPF 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 anyPF-constants, but onlyAF-constants[12]

Raw sockets

[edit]

Raw sockets provide a simple interface that bypasses the processing by the host's TCP/IP stack. They permit implementation of networking protocols inuser space and aid in debugging of the protocol stack.[13] Raw sockets are used by some services, such asICMP, that operate at theInternet Layer of the TCP/IP model.

Blocking and non-blocking mode

[edit]

Berkeley 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 torace conditions due to variances in network link speed.[citation needed]

A socket is typically set to blocking or non-blocking mode using the functionsfcntl andioctl.

Terminating sockets

[edit]

The operating system does not release the resources allocated to a socket until the socket is closed. This is especially important if theconnect 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 aTIME_WAIT state, on the server side, for up to 4 minutes.[15]

OnSVR4 systems, use ofclose() may discard data. The use ofshutdown() or SO_LINGER may be required on these systems to guarantee delivery of all data.[16]

Client-server example using TCP

[edit]

TheTransmission Control Protocol (TCP) is aconnection-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 thesocket() function with the parameters for the protocol family (PF INET,PF_INET6), the socket mode forstream sockets (SOCK_STREAM), and the IP protocol identifier for TCP (IPPROTO_TCP).

Server

[edit]

Establishing a TCP server involves the following basic steps:

  • Creating a TCP socket with a call tosocket().
  • Binding the socket to the listening portbind() after setting the port number.
  • Preparing the socket to listen for connections (making it a listening socket), with a call tolisten().
  • Accepting incoming connections (accept()). This blocks the process until an incoming connection is received, and returns a socket descriptor for the accepted connection. The initial descriptor remains a listening descriptor, andaccept() can be called again at any time with this socket, until it is closed.
  • Communicating with the remote host with the API functionssend() andrecv(), as well as with the general-purpose functionswrite() andread().
  • Closing each socket that was opened after use with functionclose()

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>intmain(void){intsockfd=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);if(sockfd==-1){fprintf(stderr,"Failed to create socket!\n");returnEXIT_FAILURE;}structsockaddr_insa={.sin_family=AF_INET,.sin_port=htons(1100),.sin_addr.s_addr=htonl(INADDR_ANY)};if(bind(sockfd,(structsockaddr*)&sa,sizeof(sa))==-1){fprintf(stderr,"Failed to bind socket!\n");close(sockfd);returnEXIT_FAILURE;}if(listen(sockfd,10)==-1){fprintf(stderr,"Failed to listen on socket!\n");close(sockfd);returnEXIT_FAILURE;}while(true){intconnfd=accept(sockfd,NULL,NULL);if(connfd==-1){fprintf(stderr,"Failed to accept connection!\n");close(sockfd);returnEXIT_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);returnEXIT_FAILURE;}close(connfd);}close(connfd);returnEXIT_SUCCESS;}

Client

[edit]

Programming a TCP client application involves the following steps:

  • Creating a TCP socket.
  • Connecting to the server (connect()), by passing asockaddr_in structure with thesin_family set toAF_INET,sin_port set to the port the endpoint is listening (in network byte order), andsin_addr set to the IP address of the listening server (also in network byte order).
  • Communicating with the remote host with the API functionssend() andrecv(), as well as with the general-purpose functionswrite() andread().
  • Closing each socket that was opened after use with functionclose().
#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>intmain(void){intsockfd=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);if(sockfd==-1){fprintf(stderr,"Failed to create socket!\n");returnEXIT_FAILURE;}structsockaddr_insa={.sin_family=AF_INET,.sin_port=htons(1100),};intres=inet_pton(AF_INET,"192.168.1.3",&sa.sin_addr);if(connect(sockfd,(structsockaddr*)&sa,sizeof(sa))==-1){fprintf(stderr,"Failed to establish connection!\n");close(sockfd);returnEXIT_FAILURE;}// perform read write operations...close(sockfd);returnEXIT_SUCCESS;}

Client-server example using UDP

[edit]

TheUser Datagram Protocol (UDP) is aconnectionless 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, theTSAPs), is completely disjoint from that of TCP ports.

Server

[edit]

An application may set up a UDP server on port number7654 as follows. The programs contains an infinite loop that receives UDP datagrams with functionrecvfrom().

#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>intmain(void){structsockaddr_insa={.sin_family=AF_INET,.sin_addr.s_addr=htonl(INADDR_ANY),.sin_port=htons(7654)};charbuffer[1024];ssize_trecsize;socklen_tfromlen=sizeof(sa);intsock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);if(bind(sock,(structsockaddr*)&sa,sizeof(sa))==-1){fprintf(stderr,"Failed to bind socket!\n");close(sock);returnEXIT_FAILURE;}while(true){recsize=recvfrom(sock,(void*)buffer,sizeofbuffer,0,(structsockaddr*)&sa,&fromlen);if(recsize<0){fprintf(stderr,"%s\n",strerror(errno));returnEXIT_FAILURE;}printf("recsize: %d\n ",(int)recsize);sleep(1);printf("datagram: %.*s\n",(int)recsize,buffer);}}

Client

[edit]

The following is a client program for sending a UDP packet containing the string "Hello, world!" to address127.0.0.1 at port number7654.

#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>intmain(void){structsockaddr_insa={// 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)};charbuffer[200];strcpy(buffer,"Hello, world!");// Create an Internet, datagram socket using UDPintsock=socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP);if(sock==-1){// If socket failed to initialize, exitfprintf(stderr,"Failed to create socket!\n");returnEXIT_FAILURE;}// Send message using sendto()intbytes_sent=sendto(sock,buffer,strlen(buffer),0,(structsockaddr*)&sa,sizeof(sa));if(bytes_sent<0){fprintf(stderr,"Error sending packet: %s\n",strerror(errno));returnEXIT_FAILURE;}close(sock);// close the socketreturn0;}

In this code,buffer is a pointer to the data to be sent, andbuffer_length specifies the size of the data.

References

[edit]
  1. ^E. g. in theRuby programming languageclass Socket
  2. ^"— POSIX.1-2008 specification". Opengroup.org. Retrieved2012-07-26.
  3. ^"The Organization of Networks in Plan 9".
  4. ^"Linux TCP/IP stack as VFS plugin".
  5. ^Stevens & Rago 2013, p. 607.
  6. ^POSIX.1-2004
  7. ^gethostbyname(3) – FreeBSD Library FunctionsManual
  8. ^Conill, Ariadne (March 27, 2022)."the tragedy of gethostbyname".ariadne.space.
  9. ^nsswitch.conf(5) – FreeBSD File FormatsManual
  10. ^"netrom(4) — ax25-tools — Debian experimental — Debian Manpages".
  11. ^UNIX Network Programming Volume 1, Third Edition: The Sockets Networking API, W. Richard Stevens, Bill Fenner, Andrew M. Rudoff, Addison Wesley, 2003.
  12. ^"The Open Group Base Specifications Issue 7". Pubs.opengroup.org. Retrieved2012-07-26.
  13. ^"TCP/IP raw sockets - Win32 apps". 19 January 2022.
  14. ^"Beej's Guide to Network Programming". Beej.us. 2007-05-05. Retrieved2012-07-26.
  15. ^"terminating sockets". Softlab.ntua.gr. Retrieved2012-07-26.
  16. ^"ntua.gr - Programming UNIX Sockets in C - Frequently Asked Questions: Questions regarding both Clients and Servers (TCP/SOCK_STREAM)". Softlab.ntua.gr. Retrieved2012-07-26.

Thede 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 fromthe Austin website.

The IPv6 extensions to the base socket API are documented in RFC 3493 and RFC 3542.

External links

[edit]
Retrieved from "https://en.wikipedia.org/w/index.php?title=Berkeley_sockets&oldid=1322003418"
Categories:
Hidden categories:

[8]ページ先頭

©2009-2026 Movatter.jp