Berkeley sockets
Encyclopedia
The Berkeley sockets application programming interface
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 (API) comprises a library for developing applications in the C programming language
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....

 that perform inter-process communication
Inter-process communication
In computing, Inter-process communication is a set of methods for the exchange of data among multiple threads in one or more processes. Processes may be running on one or more computers connected by a network. IPC methods are divided into methods for message passing, synchronization, shared...

, most commonly for communications across a computer network
Computer network
A computer network, often simply referred to as a network, is a collection of hardware components and computers interconnected by communication channels that allow sharing of resources and information....

.

Berkeley sockets (also known as the BSD
Berkeley Software Distribution
Berkeley Software Distribution is a Unix operating system derivative developed and distributed by the Computer Systems Research Group of the University of California, Berkeley, from 1977 to 1995...

 socket API) originated with the 4.2BSD Unix
Unix
Unix is a multitasking, multi-user computer operating system originally developed in 1969 by a group of AT&T employees at Bell Labs, including Ken Thompson, Dennis Ritchie, Brian Kernighan, Douglas McIlroy, and Joe Ossanna...

 operating system
Operating system
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...

 (released in 1983) as an API. Only in 1989, however, could UC Berkeley
University of California, Berkeley
The University of California, Berkeley , is a teaching and research university established in 1868 and located in Berkeley, California, USA...

 release versions of its operating system and networking library free from the licensing constraints of AT&T
AT&T
AT&T Inc. is an American multinational telecommunications corporation headquartered in Whitacre Tower, Dallas, Texas, United States. It is the largest provider of mobile telephony and fixed telephony in the United States, and is also a provider of broadband and subscription television services...

's copyright-protected Unix.

The Berkeley socket API forms the de facto
De facto
De facto is a Latin expression that means "concerning fact." In law, it often means "in practice but not necessarily ordained by law" or "in practice or actuality, but not officially established." It is commonly used in contrast to de jure when referring to matters of law, governance, or...

standard abstraction
Abstraction (computer science)
In computer science, abstraction is the process by which data and programs are defined with a representation similar to its pictorial meaning as rooted in the more complex realm of human life and language with their higher need of summarization and categorization , while hiding away the...

 for network sockets. Most other programming languages use an interface similar to the C API. The API is also used for Unix domain socket
Unix domain socket
A Unix domain socket or IPC socket is a data communications endpoint for exchanging data between processes executing within the same host operating system. While similar in functionality to...

s, which are an interface to interprocess communication (IPC) channels within a single computer.

The STREAMS-based Transport Layer Interface
Transport Layer Interface
In computer networking, the Transport Layer Interface was the networking API provided by AT&T UNIX System V Release 3 in 1987 and continued into Release 4 . TLI was the System V counterpart to the BSD sockets programming interface, which was also provided in UNIX System V Release 4...

 (TLI) API offers an alternative to the socket API. However, recent systems that provide the TLI API also provide the Berkeley socket API.

Berkeley socket interface

The Berkeley socket interface is an application programming interface
Application programming interface
An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

 (API) to code applications performing communication between hosts
Server (computing)
In the context of client-server architecture, a server is a computer program running to serve the requests of other programs, the "clients". Thus, the "server" performs some computational task on behalf of "clients"...

 or between processes on one computer, using the concept of an Internet socket
Internet socket
In computer networking, an Internet socket or network socket is an endpoint of a bidirectional inter-process communication flow across an Internet Protocol-based computer network, such as the Internet....

. It can work with many different Input/output
Input/output
In computing, input/output, or I/O, refers to the communication between an information processing system , and the outside world, possibly a human, or another information processing system. Inputs are the signals or data received by the system, and outputs are the signals or data sent from it...

 devices, although support for these depends on the operating-system
Operating system
An operating system is a set of programs that manage computer hardware resources and provide common services for application software. The operating system is the most important type of system software in a computer system...

 implementation. This interface implementation is the original API of the Internet Protocol Suite
Internet protocol suite
The Internet protocol suite is the set of communications protocols used for the Internet and other similar networks. It is commonly known as TCP/IP from its most important protocols: Transmission Control Protocol and Internet Protocol , which were the first networking protocols defined in this...

 (TCP/IP). It was first developed at the University of California, Berkeley
University of California, Berkeley
The University of California, Berkeley , is a teaching and research university established in 1868 and located in Berkeley, California, USA...

 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.

Socket interfaces are accessible at three different levels. The most detailed and powerful method is control at the raw socket
Raw socket
In computer networking, a raw socket is a socket that allows direct sending and receiving of network packets by applications, bypassing all encapsulation in the networking software of the operating system. Most socket application programming interfaces , especially those based on Berkeley sockets,...

 level. Very few applications need the degree of control over 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 including Microsoft Windows
Microsoft Windows
Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...

, have implemented support for it.

BSD vs POSIX

As the Berkeley socket API evolved over time, and ultimately into the POSIX socket API, certain functions were deprecated or even removed and replaced by others. The POSIX API is also designed to be reentrant. These features now set the classic BSD API from the POSIX API apart.
Action BSD POSIX
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
Getaddrinfo
The getaddrinfo and getnameinfo functions are part of the POSIX standard application programming interface for converting domain name system hostnames and IP addresses between their human-readable text representations and structured binary formats for the operating system's networking...

Reverse lookup for host name/service gethostbyaddr, getservbyport getnameinfo

Header files

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:
Core BSD socket functions and data structures.
AF_INET and AF_INET6 address families and their corresponding protocol families PF_INET and PF_INET6. Widely used on the Internet, these include IP addresses and TCP and UDP port numbers.
PF_UNIX/PF_LOCAL address family. Used for local communication between programs running on the same computer. Not used on networks.
Functions for manipulating numeric IP addresses.
Functions for translating protocol names and host names into numeric addresses. Searches local data as well as DNS.

Socket API functions

This list is a summary of functions or methods provided by the Berkeley sockets API library:
  • socket creates a new socket of a certain socket 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 port number and IP address.
  • 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 and recv, or write and read, or sendto and recvfrom, are used for sending and receiving data to/from a remote socket.
  • close causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated.
  • gethostbyname and gethostbyaddr are used to resolve host names and addresses. IPv4 only.
  • select is used to prune a provided list of sockets for those that are 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.


Further details are given below.

socket

socket creates an endpoint for communication and returns a file descriptor
File descriptor
In computer programming, a file descriptor is an abstract indicator for accessing a file. The term is generally used in POSIX operating systems...

 for the socket. socket takes three arguments:
  • domain, which specifies the protocol family of the created socket. For example:
    • PF_INET for network protocol IPv4
      IPv4
      Internet Protocol version 4 is the fourth revision in the development of the Internet Protocol and the first version of the protocol to be widely deployed. Together with IPv6, it is at the core of standards-based internetworking methods of the Internet...

       or
    • PF_INET6 for IPv6
      IPv6
      Internet Protocol version 6 is a version of the Internet Protocol . It is designed to succeed the Internet Protocol version 4...

      .
    • 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 specifying the actual transport protocol to use. The most common are IPPROTO TCP
    Transmission Control Protocol
    The Transmission Control Protocol is one of the core protocols of the Internet Protocol Suite. TCP is one of the two original components of the suite, complementing the Internet Protocol , and therefore the entire suite is commonly referred to as TCP/IP...

    , IPPROTO SCTP, IPPROTO UDP
    User Datagram Protocol
    The User Datagram Protocol is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol network without requiring...

    , IPPROTO DCCP. These protocols are specified in . The value “0” 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.

Prototype:

int socket(int domain, int type, int protocol);

bind

bind assigns a socket to an address. When a socket is created using socket, it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind system call before the socket can accept connections to other hosts. bind takes three arguments:
  • sockfd, a descriptor representing the socket to perform the bind on.
  • my_addr, a pointer to a sockaddr structure representing the address to bind to.
  • addrlen, a socklen_t field specifying the size of the sockaddr structure.

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

Prototype:

int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);

listen

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.

Prototype:

int listen(int sockfd, int backlog);

accept

When an application is listening for stream-oriented connections from other hosts, it is notified of such events (cf. select
Select (Unix)
select is a system call and application programming interface in Unix-like and POSIX-compliant operating systems for examining the status of file descriptors of open input/output channels...

 function) and must initialize the connection using the accept function. The accept function creates a new socket for each connection and removes the connection from the listen queue. It takes 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 a socklen_t location that specifies the size of the client address structure passed to accept. When accept returns, this location indicates how many bytes of the structure were actually used.


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

Datagram sockets do not require processing by accept since the receiver may immediately respond to the request using the listening socket.

Prototype:

int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen);

connect

The connect system call connects a socket, identified by its file descriptor, to a remote host specified by that host's address in the argument list.

Certain types of sockets are connectionless, most commonly user datagram protocol
User Datagram Protocol
The User Datagram Protocol is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol network without requiring...

 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.

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

Prototype:

int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen);

gethostbyname and gethostbyaddr

The gethostbyname and gethostbyaddr functions are used to resolve host names and addresses in the domain name system
Domain name system
The Domain Name System is a hierarchical distributed naming system for computers, services, or any resource connected to the Internet or a private network. It associates various information with domain names assigned to each of the participating entities...

 or the local host's other resolver mechanisms (e.g., /etc/hosts lookup). They return a pointer to an object of type struct hostent, which describes an Internet Protocol
Internet Protocol
The Internet Protocol is the principal communications protocol used for relaying datagrams across an internetwork using the Internet Protocol Suite...

 host. The functions take the following arguments:
  • name specifies the name of the host. For example: www.wikipedia.org
  • addr specifies a pointer to a struct in_addr containing the address of the host.
  • len specifies the length, in bytes, of addr.
  • type specifies the address family type (e.g., AF_INET) of the host address.


The functions return a NULL pointer in case of error, in which case the external integer h_errno may be checked to see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid struct 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. Furthermore, 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 function are getaddrinfo and getnameinfo
Getaddrinfo
The getaddrinfo and getnameinfo functions are part of the POSIX standard application programming interface for converting domain name system hostnames and IP addresses between their human-readable text representations and structured binary formats for the operating system's networking...

, and are based on a new addrinfo data structure.

Prototypes:

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

Protocol and address families

The socket API is a general interface for Unix networking and allows the use of various network protocols and addressing architectures.

The following lists a sampling of protocol families (preceded by the standard symbolic identifier) defined in a modern Linux
Linux
Linux is a Unix-like computer operating system assembled under the model of free and open source software development and distribution. The defining component of any Linux system is the Linux kernel, an operating system kernel first released October 5, 1991 by Linus Torvalds...

 or BSD implementation:
PF_LOCAL, PF_UNIX, PF_FILE
Local to host (pipes and file-domain)
PF_INET IP protocol family
PF_AX25 Amateur Radio AX.25
PF_IPX Novell Internet Protocol
PF_APPLETALK Appletalk DDP
PF_NETROM Amateur radio NetROM
PF_BRIDGE Multiprotocol bridge
PF_ATMPVC ATM PVCs
PF_X25 Reserved for X.25 project
PF_INET6 IP version 6
PF_ROSE Amateur Radio X.25 PLP
PF_DECnet Reserved for DECnet project
PF_NETBEUI Reserved for 802.2LLC project
PF_SECURITY Security callback pseudo AF
PF_KEY PF_KEY key management API
PF_NETLINK, PF_ROUTE
routing API
PF_PACKET Packet family
PF_ASH Ash
PF_ECONET Acorn Econet
PF_ATMSVC ATM SVCs
PF_SNA Linux SNA Project
PF_IRDA IRDA sockets
PF_PPPOX PPPoX sockets
PF_WANPIPE Wanpipe API sockets
PF_BLUETOOTH Bluetooth sockets

A socket for communications using any family is created with the socket function (see above), 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 prefix AF_ instead of PF_. The AF_-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 AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

However, the current POSIX.1—2008 specification doesn't specify any of PF_-constants, but only AF_-constants

Options for sockets

After creating a socket, it is possible to set options on it. Some of the more common options are:
  • TCP_NODELAY disables the Nagle algorithm.
  • SO_KEEPALIVE enables periodic 'liveness' pings, if supported by the OS.

Blocking vs. non-blocking mode

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) 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 http://beej.us/guide/bgnet/. It also may cause problems if a socket continues to listen: a program may hang as the socket waits for data that may never arrive. 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 socket is typically set to blocking or nonblocking mode using the fcntl or ioctl
Ioctl
In computing, ioctl, short for input/output control, is a system call for device-specific operations and other operations which cannot be expressed by regular system calls. It takes a parameter specifying a request code; the effect of a call depends completely on the request code. Request codes are...

functions.

Terminating sockets

The operating system does not release the resources allocated to a socket until a close call occurs on the socket descriptor. This is especially important if the connect call fails and may be retried. Each successful call to socket must have a matching call to close in all possible execution paths. The header file defines the close function.

When the close system call is initiated by an application, only the interface to the socket is destroyed, not the socket itself. It is the kernel's responsibility to destroy the socket internally. Sometimes, a socket may enter a TIME_WAIT state, on the server side, for up to 4 minutes.

On SVR4 systems use of close may discard data. The use of shutdown or SO_LINGER may be required on these systems to guarantee delivery of all data.

Client-server example using TCP

The Transmission Control Protocol
Transmission Control Protocol
The Transmission Control Protocol is one of the core protocols of the Internet Protocol Suite. TCP is one of the two original components of the suite, complementing the Internet Protocol , and therefore the entire suite is commonly referred to as TCP/IP...

 (TCP) is a connection-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 the socket function with the parameters for the protocol family (PF INET
PF INET
In computer networking, programmers using Berkeley sockets use PF_INET to represent the protocol family INET for Internet sockets....

, PF_INET6), the socket mode for Stream Sockets (SOCK_STREAM), and the IP protocol identifier for TCP (IPPROTO_TCP).

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 memset), and the sin_family (AF_INET), 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.



/* Server code in C */

#include
#include
#include
#include
#include
#include
#include
#include

int main(void)
{
struct sockaddr_in stSockAddr;
int SocketFD = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);

if(-1

SocketFD)
{
perror("can not create socket");
exit(EXIT_FAILURE);
}

memset(&stSockAddr, 0, sizeof(stSockAddr));

stSockAddr.sin_family = AF_INET;
stSockAddr.sin_port = htons(1100);
stSockAddr.sin_addr.s_addr = INADDR_ANY;

if(-1

bind(SocketFD,(struct sockaddr *)&stSockAddr, sizeof(stSockAddr)))
{
perror("error bind failed");
close(SocketFD);
exit(EXIT_FAILURE);
}

if(-1 listen(SocketFD, 10))
{
perror("error listen failed");
close(SocketFD);
exit(EXIT_FAILURE);
}

for
{
int ConnectFD = accept(SocketFD, NULL, NULL);

if(0 > ConnectFD)
{
perror("error accept failed");
close(SocketFD);
exit(EXIT_FAILURE);
}

/* perform read write operations ...
read(ConnectFD,buff,size)*/

shutdown(ConnectFD, SHUT_RDWR);

close(ConnectFD);
}
}

Client

Programming a TCP client application 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, sin_port set to the port the endpoint is listening (in network byte order), and sin_addr set to the IP 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.



/* Client code in C */

#include
#include
#include
#include
#include
#include
#include
#include

int main(void)
{
struct sockaddr_in stSockAddr;
int Res;
int SocketFD = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (-1 SocketFD)
{
perror("cannot create socket");
exit(EXIT_FAILURE);
}

memset(&stSockAddr, 0, sizeof(stSockAddr));

stSockAddr.sin_family = AF_INET;
stSockAddr.sin_port = htons(1100);
Res = inet_pton(AF_INET, "192.168.1.3", &stSockAddr.sin_addr);

if (0 > Res)
{
perror("error: first parameter is not a valid address family");
close(SocketFD);
exit(EXIT_FAILURE);
}
else if (0

Res)
{
perror("char string (second parameter does not contain valid ipaddress)");
close(SocketFD);
exit(EXIT_FAILURE);
}

if (-1

connect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof(stSockAddr)))
{
perror("connect failed");
close(SocketFD);
exit(EXIT_FAILURE);
}

/* perform read write operations ... */

shutdown(SocketFD, SHUT_RDWR);

close(SocketFD);
return 0;
}

Client-server example using UDP

The User Datagram Protocol
User Datagram Protocol
The User Datagram Protocol is one of the core members of the Internet Protocol Suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol network without requiring...

 (UDP) is a connectionless 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, the TSAPs), is completely disjoint from that of TCP ports.

Server

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


  1. include
  2. include
  3. include
  4. include
  5. include
  6. include
  7. include /* for close for socket */
  8. include


int main(void)
{
int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
struct sockaddr_in sa;
char buffer[1024];
ssize_t recsize;
socklen_t fromlen;

memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
sa.sin_port = htons(7654);
fromlen = sizeof(sa);

if (-1 bind(sock,(struct sockaddr *)&sa, sizeof(sa)))
{
perror("error bind failed");
close(sock);
exit(EXIT_FAILURE);
}

for
{
printf ("recv test....\n");
recsize = recvfrom(sock, (void *)buffer, 1024, 0, (struct sockaddr *)&sa, &fromlen);
if (recsize < 0) {
fprintf(stderr, "%s\n", strerror(errno));
exit(EXIT_FAILURE);
}
printf("recsize: %z\n ", recsize);
sleep(1);
printf("datagram: %.*s\n", (int)recsize, buffer);
}
}



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 recv or other receive socket function)
  • address struct of sending peer
  • length of address struct of sending peer.

Client

A simple demonstration of sending a UDP packet containing the string "Hello World!" to address 127.0.0.1, port 7654 might look like this:

  1. include
  2. include
  3. include
  4. include
  5. include
  6. include
  7. include
  8. include
  9. include

int main(int argc, char *argv[])
{
int sock;
struct sockaddr_in sa;
int bytes_sent;
char buffer[200];

strcpy(buffer, "hello world!");

sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (-1 sock) /* if socket failed to initialize, exit */
{
printf("Error Creating Socket");
exit(EXIT_FAILURE);
}

memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = inet_addr("127.0.0.1");
sa.sin_port = htons(7654);

bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, sizeof sa);
if (bytes_sent < 0) {
printf("Error sending packet: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}

close(sock); /* close the socket */
return 0;
}



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

See also

  • Internet socket
    Internet socket
    In computer networking, an Internet socket or network socket is an endpoint of a bidirectional inter-process communication flow across an Internet Protocol-based computer network, such as the Internet....

  • Unix domain socket
    Unix domain socket
    A Unix domain socket or IPC socket is a data communications endpoint for exchanging data between processes executing within the same host operating system. While similar in functionality to...

  • Winsock
    Winsock
    In computing, the Windows Sockets API , which was later shortened to Winsock, is a technical specification that defines how Windows network software should access network services, especially TCP/IP. It defines a standard interface between a Windows TCP/IP client application and the underlying...

    , the Berkeley sockets-based application programming interface
    Application programming interface
    An application programming interface is a source code based specification intended to be used as an interface by software components to communicate with each other...

     for networking on Microsoft Windows
    Microsoft Windows
    Microsoft Windows is a series of operating systems produced by Microsoft.Microsoft introduced an operating environment named Windows on November 20, 1985 as an add-on to MS-DOS in response to the growing interest in graphical user interfaces . Microsoft Windows came to dominate the world's personal...


External links

The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK