FACTOID # 119: The United States has the world's highest number of McDonald’s restaurants per capita. Americans also die of obesity more often than any other nation, with more deaths than Mexico, Germany, Spain, Austria and Canada combined.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

SEARCH ALL

FACTS & STATISTICS    Advanced view

Search encyclopedia, statistics and forums:

 

 

(* = Graphable)

 

 


Encyclopedia > Berkeley Sockets

The Berkeley sockets application programming interface (API) comprises a library for developing applications in the C programming language that perform inter-process communication, most commonly across a computer network. API and Api redirect here. ... Illustration of an application which may use libvorbisfile. ... C is a general-purpose, block structured, procedural, imperative computer programming language developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system. ... Inter-Process Communication (IPC) is a set of techniques for the exchange of data between two or more threads in one or more processes. ... A computer network is an interconnection of a group of computers. ...


Berkeley sockets (also known as the BSD socket API) originated with the 4.2BSD Unix operating system (released in 1983) 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. BSD redirects here. ... Filiation of Unix and Unix-like systems Unix (officially trademarked as UNIX®, sometimes also written as or ® with small caps) is a computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs including Ken Thompson, Dennis Ritchie and Douglas McIlroy. ... An operating system (OS) is the software that manages the sharing of the resources of a computer and provides programmers with an interface used to access those resources. ... Year 1983 (MCMLXXXIII) was a common year starting on Saturday (link displays the 1983 Gregorian calendar). ... Year 1989 (MCMLXXXIX) was a common year starting on Sunday (link displays 1989 Gregorian calendar). ... Sather tower (the Campanile) looking out over the San Francisco Bay and Mount Tamalpais. ... This article is about the current AT&T. For the 1885-2005 company, see American Telephone & Telegraph. ...


The Berkeley socket API forms the de facto standard abstraction for network sockets. Most other programing languages use an interface similar to the C API. De facto is a Latin expression that means in fact or in practice. It is commonly used as opposed to de jure (meaning by law) when referring to matters of law or governance or technique (such as standards), that are found in the common experience as created or developed without... In computer science, abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time. ... An Internet socket (or commonly, a socket or network socket), is a communication end-point unique to a machine communicating on an Internet Protocol-based network, such as the Internet. ...


The STREAMS-based Transport Layer Interface (TLI) API offers an alternative to the socket API. However, the Berkeley socket API predominates convincingly in popularity and in the number of implementations. STREAMS is the Unix System V networking architecture, which is an alternative to the Berkeley sockets API, although all modern systems that provide STREAMS provide sockets as well. ... In computer software, specifically networking, the Transport Layer Interface (TLI) was the networking API provided by AT&T UNIX System V Release 3. ...

Contents

Berkeley socket interface

The Berkeley socket interface, an API, allows communications between hosts or between processes on one computer, using the concept of an internet socket. It can work with many different I/O devices and drivers, although support for these depends on the operating-system implementation. This interface implementation is implicit for TCP/IP, and it is therefore one of the fundamental technologies underlying the Internet. It was first developed at the University of California, Berkeley for use on Unix systems. All modern operating systems now have some implementation of the Berkeley socket interface, as it became the standard interface for connecting to the Internet. API and Api redirect here. ... An Internet socket (or commonly, a socket or network socket), is a communication end-point unique to a machine communicating on an Internet Protocol-based network, such as the Internet. ... Energy Input: The energy placed into a reaction. ... A device driver, or software driver is a computer program allowing higher-level computer programs to interact with a computer hardware device. ... An operating system (OS) is the software that manages the sharing of the resources of a computer and provides programmers with an interface used to access those resources. ... The Internet protocol suite is the set of communications protocols that implement the protocol stack on which the Internet and most commercial networks run. ... Sather tower (the Campanile) looking out over the San Francisco Bay and Mount Tamalpais. ...


Programmers can make the socket interfaces accessible at three different levels, most powerfully and fundamentally at the raw socket level. Very few applications need the degree of control over outgoing communications that this provides, so raw sockets support was intended to be available only on computers used for developing Internet-related technologies. In recent years, most operating systems have implemented support for it anyway, including Windows XP. Raw socket is a computer networking term used to describe a socket that allows access to packet headers on incoming and outgoing packets. ... Windows redirects here. ...


The header files

Raihan-01915800140 The Berkeley socket development library has many associated header files. They include:

<sys/socket.h>
Core BSD socket functions and data structures.
<netinet/in.h>
AF_INET and AF_INET6 address families. Widely used on the Internet, these include IP addresses and TCP and UDP port numbers.
<sys/un.h>
AF_UNIX address family. Used for local communication between programs running on the same computer. Not used on networks.
<arpa/inet.h>
Functions for manipulating numeric IP addresses.
<netdb.h>
Functions for translating protocol names and host names into numeric addresses. Searches local data as well as DNS.

TCP

TCP provides the concept of a connection. A process creates a TCP socket by calling the socket() function with the parameters PF_INET or PF_INET6 and SOCK_STREAM (Stream Sockets). The Transmission Control Protocol (TCP) is one of the core protocols of the Internet protocol suite. ... In computer networking, programmers using Berkeley sockets use PF_INET to represent the protocol family INET for Internet sockets. ... Stream socket is a type of internet socket which provides a connection-oriented, sequenced, and unduplicated flow of data without record boundaries, with well-defined mechanisms for creating and destroying connections and for detecting errors. ...


Server

Setting up a simple TCP server involves the following steps:

  • Creating a TCP socket, with a call to socket().
  • Binding the socket to the listen port, with a call to bind(). Before calling bind(), a programmer must declare a sockaddr_in structure, clear it (with bzero() or memset()), and the sin_family (AF_INET or AF_INET6), and fill its sin_port (the listening port, in network byte order) fields. Converting a short int to network byte order can be done by calling the function htons() (host to network short).
  • Preparing the socket to listen for connections (making it a listening socket), with a call to listen().
  • Accepting incoming connections, via a call to accept(). This blocks until an incoming connection is received, and then returns a socket descriptor for the accepted connection. The initial descriptor remains a listening descriptor, and accept() can be called again at any time with this socket, until it is closed.
  • Communicating with the remote host, which can be done through send() and recv() or write() and read().
  • Eventually closing each socket that was opened, once it is no longer needed, using close(). Note that if there were any calls to fork(), each process must close the sockets it knew about (the kernel keeps track of how many processes have a descriptor open), and two processes should not use the same socket at once.
 // Server code in C #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> int main() { int32_t i32SocketFD = socket(PF_INET, SOCK_STREAM, 0); if(-1 == i32SocketFD) { printf("can not create socket"); exit(-1); } struct sockaddr_in stSockAddr; bzero(&stSockAddr, sizeof(stSockAddr)); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(1100); stSockAddr.sin_addr.s_addr = htonl(INADDR_ANY); if(-1 == bind(i32SocketFD,(struct sockaddr*) &stSockAddr, sizeof(stSockAddr))) { printf("error bind failed"); exit(-1); } if(-1 == listen(i32SocketFD, 10)) { printf("error listen failed"); exit(-1); } for(; ;) { int32_t i32ConnectFD = accept(i32SocketFD, NULL, NULL); if(0 > i32ConnectFD) { printf("error accept failed"); exit(-1); } // perform read write operations ... shutdown(i32ConnectFD, 2); close(i32ConnectFD); } return 0; } 

When integers or any other data are represented with multiple bytes, there is no unique way of ordering of those bytes in memory or in a transmission over some medium, and so the order is subject to arbitrary convention. ...

Client

Setting up a TCP client involves the following steps:

  • Creating a TCP socket, with a call to socket().
  • Connecting to the server with the use of connect(), passing a sockaddr_in structure with the sin_family set to AF_INET or AF_INET6, sin_port set to the port the endpoint is listening (in network byte order), and sin_addr set to the IPv4 or IPv6 address of the listening server (also in network byte order.)
  • Communicating with the server by using send() and recv() or write() and read().
  • Terminating the connection and cleaning up with a call to close(). Again, if there were any calls to fork(), each process must close() the socket.
 // Client code in C #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h> int main() { int32_t i32SocketFD = socket(PF_INET, SOCK_STREAM, 0); if(-1 == i32SocketFD) { printf("cannot create socket"); exit(-1); } struct sockaddr_in stSockAddr; bzero(&stSockAddr, sizeof(stSockAddr)); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(1101); int32_t i32Res = inet_pton(AF_INET, "192.168.1.3", (void *) &stSockAddr.sin_addr); if(0 > i32Res) { printf("error: first parameter is not a valid address family"); exit(-1); } else if(0 == i32Res) { printf("char string (second parameter does not contain valid ipaddress"); exit(-1); } if(-1 == connect(i32SocketFD,(struct sockaddr*) &stSockAddr, sizeof(stSockAddr))) { printf("connect failed"); exit(-1); } // perform read write operations ... shutdown(i32SocketFD, 2); close(i32SocketFD); return 0; } 

There are very few or no other articles that link to this one. ...

UDP

UDP consists of a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, become duplicated and arrive more than once, or even not arrive at all. Due to the minimal guarantees involved, UDP has considerably less overhead than TCP. Being connectionless means that there is no concept of a stream or connection between two hosts, instead, data arrives in datagrams (Datagram Sockets). User Datagram Protocol (UDP) is one of the core protocols of the Internet protocol suite. ... In a packet-switched network, connectionless mode transmission is transmission in which each packet is prepended with a header containing a destination address sufficient to permit the independent delivery of the packet without the aid of additional instructions. ... Datagram socket is a type of Internet socket, which is the sending or receiving point for packet delivery services. ...


UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports. A Service Access Point or SAP is an identifying label for network endpoints used in OSI networking. ...


Server

Code may set up a UDP server on port 7654 as follows:

 sock = socket(PF_INET,SOCK_DGRAM,IPPROTO_UDP); sa.sin_addr.s_addr = INADDR_ANY; sa.sin_port = htons(7654); bound = bind(sock,(struct sockaddr *)&sa, sizeof(struct sockaddr)); if (bound < 0) fprintf(stderr, "bind(): %sn",strerror(errno)); 

bind() binds the socket to an address/port pair.

 while (1) { printf ("recv test....n"); recsize = recvfrom(sock, (void *)Hz, 100, 0, (struct sockaddr *)&sa, fromlen); printf ("recsize: %dn ",recsize); if (recsize < 0) fprintf(stderr, "%sn", strerror(errno)); sleep(1); printf("datagram: %sn",Hz); } 

This infinite loop receives any UDP datagrams to port 7654 using recvfrom(). It uses the parameters:

  • socket
  • pointer to buffer for data
  • size of buffer
  • flags (same as in read or other receive socket function)
  • address struct of sending peer
  • length of address struct of sending peer.

Client

A simple demo to send a UDP packet containing "Hello World!" to address 127.0.0.1, port 7654 might look like this:

 #include <stdio.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h>//for close() for socket int main(int argc, char *argv[]) { int sock; struct sockaddr_in sa; int bytes_sent, buffer_length; char buffer[200]; sprintf(buffer, "Hello World!"); buffer_length = strlen(buffer) + 1; sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); if(-1 == sock)//if socket failed to initialize, exit { printf("Error Creating Socket"); return 0; } sa.sin_family = AF_INET; sa.sin_addr.s_addr = htonl(0x7F000001); sa.sin_port = htons(7654); bytes_sent = sendto(sock, buffer, buffer_length, 0,(struct sockaddr*) &sa, sizeof(struct sockaddr_in) ); if(bytes_sent < 0) printf("Error sending packet: %sn", strerror(errno) ); close(sock);//close the socket return 0; } 

In this code, buffer provides a pointer to the data to send, and buffer_length specifies the size of the buffer contents.


Functions

socket()

socket() creates an endpoint for communication and returns a descriptor. socket() takes three arguments: The file descriptors for input, output, and error In computer programming, a file descriptor is an abstract key for accessing a file. ...

  • domain, which specifies the protocol family of the created socket. For example:
    • PF_INET for network protocol IPv4 or
    • PF_INET6 for IPv6.
    • PF_UNIX for local socket (using a file).
  • type, one of:
    • SOCK_STREAM (reliable stream-oriented service or Stream Sockets)
    • SOCK_DGRAM (datagram service or Datagram Sockets)
    • SOCK_SEQPACKET (reliable sequenced packet service), or
    • SOCK_RAW (raw protocols atop the network layer).
  • protocol, usually set to IPPROTO_IP, which is defined as 0, to represent the default transport protocol for the specified domain and type values (TCP for PF_INET or PF_INET6 and SOCK_STREAM, UDP for those PF_ values and SOCK_DGRAM), but which can also explicitly specify a protocol. These protocols are specified in <netinet/in.h>.

The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly-assigned descriptor. Internet Protocol version 4 is the fourth iteration of the Internet Protocol (IP) and it is the first version of the protocol to be widely deployed. ... Internet Protocol version 6 (IPv6) is a network layer for packet-switched internetworks. ... Stream socket is a type of internet socket which provides a connection-oriented, sequenced, and unduplicated flow of data without record boundaries, with well-defined mechanisms for creating and destroying connections and for detecting errors. ... Datagram socket is a type of Internet socket, which is the sending or receiving point for packet delivery services. ... The Transport protocol is a protocol on the transport layer of the OSI model. ... The Transmission Control Protocol (TCP) is one of the core protocols of the Internet protocol suite. ... User Datagram Protocol (UDP) is one of the core protocols of the Internet protocol suite. ...


Prototype:

 #include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol); 

gethostbyname() and gethostbyaddr()

The gethostbyname() and gethostbyaddr() functions each return a pointer to an object of type struct hostent, which describes an internet host referenced by name or by address, respectively. This structure contains either the information obtained from a name server (ex: named), or broken-out fields from a line in /etc/hosts. If the local name server is not running these routines do a lookup in /etc/hosts. The functions take the following arguments:

  • name, which specifies the name of the host. For example: www.wikipedia.org
  • addr, which specifies a pointer to a struct in_addr containing the address of the host.
  • len, which specifies the length, in bytes, of addr.
  • type, which specifies the domain type of the host address. For example: AF_INET

The functions return a NULL pointer in case of error, in which case the external integer h_errno may be checked so see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid struct hostent * is returned.


Prototypes:

 struct hostent *gethostbyname(const char *name); struct hostent *gethostbyaddr(const void *addr, int len, int type); 

connect()

connect() It returns an integer representing the error code: 0 represents success, while -1 represents an error.


Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets. User Datagram Protocol (UDP) is one of the core protocols of the Internet protocol suite. ...


Prototype:

 #include <sys/types.h> #include <sys/socket.h> int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); 

bind()

bind() assigns a socket an address. When a socket is created using socket(), it is given an address family, but not assigned an address. Before a socket may accept incoming connections, it must be bound. bind() takes three arguments:

  • sockfd, a descriptor representing the socket to perform the bind on
  • serv_addr, a pointer to a sockaddr structure representing the address to bind to.
  • addrlen, a socklen_t field representing the length of the sockaddr structure.

It returns 0 on success and -1 if an error occurs.


Prototype:

 #include <sys/types.h> #include <sys/socket.h> int bind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen); 

listen()

listen() prepares a bound socket to accept incoming connections. This function is only applicable to the SOCK_STREAM and SOCK_SEQPACKET socket types. It takes 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.


Prototype:

 #include <sys/socket.h> int listen(int sockfd, int backlog); 

accept()

accept() is used to accept a connection request from a remote host. It takes the following arguments:

  • sockfd, the descriptor of the listening socket to accept the connection from.
  • cliaddr, a pointer to the sockaddr structure that accept() should put the client's address information into.
  • addrlen, a pointer to the socklen_t integer that will indicate to accept() how large the sockaddr structure pointed to by cliaddr is. When accept() returns, the socklen_t integer then indicates how many bytes of the cliaddr structure were actually used.

The function returns a socket corresponding to the accepted connection, or -1 if an error occurs.


Prototype:

 #include <sys/types.h> #include <sys/socket.h> int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen); 

Blocking vs. nonblocking

Berkeley sockets can operate in one of two modes: blocking or non-blocking. A blocking socket will not return control until it has sent (or received) all the data specified for the operation. This may cause problems if a socket continues to listen: a program may hang as the socket waits for data that may never arrive.


A socket is typically set to blocking or nonblocking mode using the fcntl() or ioctl() functions. In computing, the system call ioctl (IPA: ), found on Unix-like systems, allows an application to control or communicate with a device driver outside the usual read/write of data. ...


Cleaning up

The system will not release the resources allocated by the socket() call until a close() call occurs. This is especially important if the connect() call fails and may be retried. Each call to socket() must have a matching call to close() in all possible execution paths. Include <unistd.h> for the close function.


When an issue to the close() system call is made only the interface to the socket gets closed, not the socket itself. It is up to the kernel to close the socket. Sometimes, for really technical reasons, the socket is kept alive for a few minutes after you close it. It is normal, for example for the socket to go into a TIME_WAIT state, on the server side, for a few minutes. The official standard says that it should be 4 minutes.[1]


See also

A computer network is an interconnection of a group of computers. ... An Internet socket (or commonly, a socket or network socket), is a communication end-point unique to a machine communicating on an Internet Protocol-based network, such as the Internet. ... A Unix domain socket or IPC socket (inter-procedure call socket) is a virtual socket, similar to an internet socket that is used in POSIX operating systems for inter-process communication. ... Windows Sockets API version 2. ... API and Api redirect here. ... Windows redirects here. ...

References

The "de 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 from the Austin website.


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


External links

This article was originally based on material from the Free On-line Dictionary of Computing, which is licensed under the GFDL. The man page on man Almost all substantial UNIX and Unix-like operating systems have extensive documentation known as man pages (short for manual pages). The Unix command used to display them is man. ... Linux Journal is a monthly magazine published by SpecializedSystemsConsultants (SSC) of Seattle, first published in March 1994. ... This article does not cite any references or sources. ... “GFDL” redirects here. ...


  Results from FactBites:
 
Understanding Sockets in Unix, NT, and Java (5304 words)
Sockets were added to the Microsoft Windows world in the form of the Winsock API, and to the Java world as Socket and ServerSocket objects in the java.net package.
The socket descriptor sd1 and the socket address structure sas1 are declared in the same manner as in the server program, which illustrates the similarity between the Windows implementation of sockets and the Unix implementation.
Sockets do not need to be connected in order to transmit data, which is transmitted in discrete packets called datagrams.
  More results at FactBites »


 
 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your comments

Want to know more?
Search encyclopedia, statistics and forums:

 


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms, 1022, m