8 8 int s; /* socket (Bulletproof web design) */ /*
8 8 int s; /* socket */ /* * AF_INET: protocol family for IPv4 * SOCK_STREAM: connection-oriented socket * IPPROTO_TCP: use TCP on top of IPv4 */ s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s < 0) { perror( socket ); exit(1); /*NOTREACHED*/ } close(s); While read(2) or write(2) is possible for sockets, we normally need to supply more information, such as peer s address, to get the data stream to reach the peer. There are additional system calls specifically provided for sockets, such as sendmsg(2), sendto(3), recvmsg(2), and recvfrom(3). Since we need to identify the peer when accessing the network, we need to denote it either by: Using connect(2) to make the socket a connected socket. The peer s address will be kept in the system, and you can use read(2) or write(2) after connect(2). Using sendto(3) or sendmsg(2) to denote the peer every time you transmit data to the socket. For connection-oriented (TCP) sockets, there are two sides: client side, which makes active connection, and server side, which awaits connection from the client passively. connect(2) is mandatory for the client side. bind(2), listen(2), and accept(2) are mandatory for the server side. (See Figure 1.3.) For connectionless (UDP) sockets, connect(2) is not mandatory. To receive traffic from other peers, bind(2) is mandatory. (See Figure 1.4.) To denote TCP/UDP endpoints, IP address and port number are necessary. To carry the endpoint information, we use a C structure called sockaddr (short for socket addresses ). sockaddr for IPv4 is defined in the following code segment. Fields that appear on wire (sin_port and sin_addr) are in network byte order; other fields are in host byte order. /* * Note: the definition is based on 4.4BSD socket API. * Linux/Solaris has no sin_len field. */ struct sockaddr_in { u_int8_t sin_len; /* length of sockaddr */ u_int8_t sin_family; /* address family */
Do you want truly affordable web hosting? With us, what you see is what you get, just click on affordable web hosting services.