|
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. 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. The Berkeley socket API forms the de facto standard abstraction for network sockets. Most other programming languages use an interface similar to the C API. 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.
Berkeley socket interfaceThe 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. 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. The header filesThe Berkeley socket development library has many associated header files. They include:
TCPTCP provides the concept of a connection. A process creates a TCP socket by calling the ServerSetting up a simple TCP server involves the following steps:
/* 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(void) { int i32SocketFD = socket(PF_INET, SOCK_STREAM, 0); if(-1 == i32SocketFD) { printf("can not create socket"); exit(-1); } struct sockaddr_in stSockAddr; memset(&stSockAddr, 0, sizeof(stSockAddr)); stSockAddr.sin_family = PF_INET; stSockAddr.sin_port = htons(1100); stSockAddr.sin_addr.s_addr = htonl(INADDR_ANY); if(-1 == bind(i32SocketFD,(const void *)&stSockAddr, sizeof(stSockAddr))) { printf("error bind failed"); exit(-1); } if(-1 == listen(i32SocketFD, 10)) { printf("error listen failed"); exit(-1); } for(; ;) { int 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; } ClientSetting up a TCP client involves the following steps:
/* 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(void) { int i32SocketFD = socket(PF_INET, SOCK_STREAM, 0); if(-1 == i32SocketFD) { printf("cannot create socket"); exit(-1); } struct sockaddr_in stSockAddr; memset(&stSockAddr, 0, sizeof(stSockAddr)); stSockAddr.sin_family = PF_INET; stSockAddr.sin_port = htons(1100); int32_t i32Res = inet_pton(PF_INET, "192.168.1.3", &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, (const void *)&stSockAddr, sizeof(stSockAddr))) { printf("connect failed"); exit(-1); } /* perform read write operations ... */ shutdown(i32SocketFD, 2); close(i32SocketFD); return 0; } UDPUDP 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). UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports. ServerCode 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(): %s\n",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); if (recsize < 0) { const char *error = strerror(errno); /* catch errno before printf changes it */ printf ("recsize: %d\n ",recsize); fprintf(stderr, "%s\n", error); } else { printf ("recsize: %d\n ",recsize); } sleep(1); printf("datagram: %s\n",Hz); } This infinite loop receives any UDP datagrams to port 7654 using recvfrom(). It uses the parameters:
ClientA 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 = PF_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: %s\n", strerror(errno) ); close(sock); /* close the socket */ return 0; } In this code, Functionssocket()
The function returns -1 if an error occurred. Otherwise, it returns an integer representing the newly-assigned descriptor. Prototype#include <sys/types.h> #include <sys/socket.h> int socket(int domain, int type, int protocol); gethostbyname() and gethostbyaddr()The
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. Prototypesstruct hostent *gethostbyname(const char *name); struct hostent *gethostbyaddr(const void *addr, int len, int type); connect()
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. Prototype#include <sys/types.h> #include <sys/socket.h> int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen); bind()
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()
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()
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. nonblockingBerkeley 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 is true only in Linux systems. In other systems, such as FreeBSD, it is normal for a blocking socket not to send all the data. Always check the return value to find out how many bytes have been sent/received. It’s up to you to send the rest of the string[1]. 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. A socket is typically set to blocking or nonblocking mode using the Cleaning upThe system will not release the resources allocated by the When an issue to the See also
ReferencesThe "de jure" standard definition of the Sockets interface is contained in the POSIX standard, known as:
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. |
This article is from Wikipedia. All text is available under the terms of the GNU Free Documentation License.
Mercedes Car
This site monitored by SitePinger.net