Contained WithinFind More DocumentationFeatured Support Resources | Download this book in PDF (337 KB)
Chapter 2 Programming With SocketsThis chapter presents the socket interface and illustrates it with sample programs. The programs demonstrate the Internet domain sockets. Sockets are Multithread SafeThe interface described in this chapter is multithread safe. Applications that contain socket function calls can be used freely in a multithreaded application. Note, however, that the degree of concurrency available to applications is not specified. SunOS 4 Binary CompatibilityTwo major changes from SunOS 4 hold true for SunOS 5 releases. The binary compatibility package allows SunOS 4-based dynamically linked socket applications to run on SunOS 5.
What Are Sockets?Sockets are the Berkeley UNIX interface to network protocols. They have been an integral part of SunOS releases since 1981. They are commonly referred to as Berkeley sockets or BSD sockets. Beginning in Solaris 7, the XNS 5 (Unix98) Socket interfaces (which differ slightly from the BSD sockets) are also available. The XNS 5 (Unix98) Socket interfaces are documented in the following man pages: accept(3XN), bind(3XN), connect(3XN), endhostent(3XN), endnetent(3XN), endprotoent(3XN), endservent(3XN), gethostbyaddr(3XN), gethostbyname(3XN), gethostent(3XN), gethostname(3XN), getnetbyaddr(3XN), getnetbyname(3XN), getnetent(3XN), getpeername(3XN), getprotobyname(3XN), getprotobynumber(3XN), getprotoent(3XN), getservbyname(3XN), getservbyport(3XN), getservent(3XN), getsockname(3XN), getsockopt(3XN), htonl(3XN), htons(3XN), inet_addr(3XN), inet_lnaof(3XN), inet_makeaddr(3XN), inet_netof(3XN), inet_network(3XN), inet_ntoa(3XN), listen(3XN), ntohl(3XN), ntohs(3XN), recv(3XN), recvfrom(3XN), recvmsg(3XN), send(3XN), sendmsg(3XN), sendto(3XN), sethostent(3XN), setnetent(3XN), setprotoent(3XN), setservent(3XN), setsockopt(3XN), shutdown(3XN), socket(3XN), and socketpair(3XN). The traditional SunOS 5 BSD Socket behaviour is documented in the corresponding 3N man pages. See the standards(5) man page for information on building applications that use the XNS 5 (Unix98) socket interface. Since the days of early UNIX, applications have used the file system model of input/output to access devices and files. The file system model is sometimes called open-close-read-write after the basic function calls used in this model. However, the interaction between user processes and network protocols are more complex than the interaction between user processes and I/O devices. A socket is an endpoint of communication to which a name can be bound. A socket has a type and one associated process. Sockets were designed to implement the client-server model for interprocess communication where:
To address these issues and others, sockets are designed to accommodate network protocols, while still behaving like UNIX files or devices whenever it makes sense. Applications create sockets when they are needed. Sockets work with the open(), close(), read(), and write() function calls, and the operating system can differentiate between the file descriptors for files, and file descriptors for sockets. UNIX domain sockets are named with UNIX paths. For example, a socket might be named /tmp/foo. UNIX domain sockets communicate only between processes on a single host. Sockets in the UNIX domain are not considered part of the network protocols because they can only be used to communicate with processes within the same UNIX system. They are rarely used today and are only briefly covered in this manual. Socket LibrariesThe socket interface routines are in a library that must be linked with the application. The libraries libsocket.so and libsocket.a are contained in /usr/lib with the rest of the system service libraries. The difference is that libsocket.so is used for dynamic linking, whereas libsocket.a is used for static linking. Note - Static linking is strongly discouraged. Socket TypesSocket types define the communication properties visible to a user. The Internet domain sockets provide access to the TCP/IP transport protocols. The Internet domain is identified by the value Three types of sockets are supported:
See "Selecting Specific Protocols" for further information. Socket TutorialThis section covers the basic methodologies of using sockets. Socket CreationThe socket() call creates a socket in the specified domain and of the specified type.
If the protocol is unspecified (a value of 0), the system selects a protocol that supports the requested socket type. The socket handle (a file descriptor) is returned. The domain is specified by one of the constants defined in sys/socket.h. Constants named
Socket types are defined in sys/socket.h. These types--
This call results in a stream socket with the TCP protocol providing the underlying communication. The following creates a datagram socket for intramachine use:
Use the default protocol (the protocol argument is 0) in most situations. You can specify a protocol other than the default, as described in "Advanced Topics". Binding Local NamesA socket is created with no name. A remote process has no way to refer to a socket until an address is bound to it. Communicating processes are connected through addresses. In the Internet domain, a connection is composed of local and remote addresses, and local and remote ports. In the UNIX domain, a connection is composed of (usually) one or two path names. In most domains, connections must be unique. In the Internet domain, there can never be duplicate ordered sets, such as: protocol, local address, local port, foreign address, foreign port. UNIX domain sockets need not always be bound to a name, but, when bound, there can never be duplicate ordered sets such as: local pathname or foreign pathname. The path names cannot refer to existing files. The bind() call allows a process to specify the local address of the socket. This forms the set local address, local port (or local pathname) while connect() and accept() complete a socket's association by fixing the remote half of the address tuple. The bind() function call is used as follows:
The socket handle is s. The bound name is a byte string that is interpreted by the supporting protocol(s). Internet domain names contain an Internet address and port number. UNIX domain names contain a path name and a family. Example 2-1 shows binding the name /tmp/foo to a UNIX domain socket. Example 2-1 Bind Name to Socket
When determining the size of an The file name referred to in addr.sun_path is created as a socket in the system file name space. The caller must have write permission in the directory where addr.sun_path is created. The file should be deleted by the caller when it is no longer needed. Binding an Internet address is more complicated but the call is similar: The content of the address sin is described in "Address Binding", where Internet address bindings are discussed. Connection EstablishmentConnection establishment is usually asymmetric, with one process acting as the client and the other as the server. The server binds a socket to a well-known address associated with the service and blocks on its socket for a connect request. An unrelated process can then connect to the server. The client requests services from the server by initiating a connection to the server's socket. On the client side, the connect() call initiates a connection. In the UNIX domain, this might appear as:
In the Internet domain it might appear as:
If the client's socket is unbound at the time of the connect call, the system automatically selects and binds a name to the socket. See "Signals and Process Group ID". This is the usual way that local addresses are bound to a socket on the client side. In the examples that follow, only To receive a client's connection, a server must perform two steps after binding its socket. The first is to indicate how many connection requests can be queued. The second step is to accept a connection:
The socket handle s is the socket bound to the address to which the connection request is sent. The second parameter of listen() specifies the maximum number of outstanding connections that might be queued. from is a structure that is filled with the address of the client. A NULL pointer might be passed. fromlen is the length of the structure. (In the UNIX domain, from is declared a struct sockaddr_un.) accept() normally blocks. accept() returns a new socket descriptor that is connected to the requesting client. The value of fromlen is changed to the actual size of the address. A server cannot indicate that it accepts connections only from specific addresses. The server can check the from address returned by accept() and close a connection with an unacceptable client. A server can accept connections on more than one socket, or avoid blocking on the accept call. These techniques are presented in "Advanced Topics". Connection ErrorsAn error is returned if the connection is unsuccessful (however, an address bound by the system remains). Otherwise, the socket is associated with the server and data transfer can begin. Table 2-2 lists some of the more common errors returned when a connection attempt fails. Table 2-2 Socket Connection Errors
Data TransferThis section describes the functions to send and receive data. You can send or receive a message with the normal read() and write() function calls:
Or the calls send() and recv() can be used:
send() and recv() are very similar to read() and write(), but the flags argument is important. The flags, defined in sys/socket.h, can be specified as a nonzero value if one or more of the following is required:
Out-of-band data is specific to stream sockets. When MSG_PEEK is specified with a recv() call, any data present is returned to the user but treated as still unread. The next read() or recv() call on the socket returns the same data. The option to send data without routing packets applied to the outgoing packets is currently used only by the routing table management process and is unlikely to be interesting to most users. Closing SocketsA A shutdown() closes shutdown(s, how); Where how is defined as:
Connecting Stream SocketsFigure 2-1 and the next two examples illustrate initiating and accepting an Internet domain stream connection. Figure 2-1 Connection-Oriented Communication Using Stream Sockets
The program in Example 2-2 is a server. It creates a socket and binds a name to it, then displays the port number. The program calls listen() to mark the socket ready to accept connection requests and initialize a queue for the requests. The rest of the program is an infinite loop. Each pass of the loop accepts a new connection and removes it from the queue, creating a new socket. The server reads and displays the messages from the socket and closes it. The use of INADDR_ANY is explained in "Address Binding". Example 2-2 Accepting an Internet Stream Connection (Server)
To initiate a connection, the client program in Example 2-3 creates a stream socket and calls connect(), specifying the address of the socket for connection. If the target socket exists and the request is accepted, the connection is complete and the program can send data. Data are delivered in sequence with no message boundaries. The connection is destroyed when either socket is closed. For more information about data representation routines, such as ntohl(), ntohs(), htons(), and htonl(), in this program, see the byteorder(3N) man page. Example 2-3 Internet Domain Stream Connection (Client)
Datagram SocketsA datagram socket provides a symmetric data exchange interface. There is no requirement for connection establishment. Each message carries the destination address. Figure 2-2 shows the flow of communication between server and client. Note - The bind() step shown below for the server is optional. Figure 2-2 Connectionless Communication Using Datagram Sockets
Datagram sockets are created as described in "Socket Creation". If a particular local address is needed, the bind() operation must precede the first data transmission. Otherwise, the system sets the local address and/or port when data is first sent. To send data, the sendto() call is used:
The s, buf, buflen, and flags parameters are the same as in connection-oriented sockets. The to and tolen values indicate the address of the intended recipient of the message. A locally detected error condition (such as an unreachable network) causes a return of -1 and errno to be set to the error number. To receive messages on a datagram socket, the recvfrom() call is used:
Before the call, fromlen is set to the size of the from buffer. On return, it is set to the size of the address from which the datagram was received. Datagram sockets can also use the connect() call to associate a socket with a specific destination address. It can then use the send() call. Any data sent on the socket without explicitly specifying a destination address is addressed to the connected peer, and only data received from that peer is delivered. Only one connected address is permitted for one socket at a time. A second connect() call changes the destination address. Connect requests on datagram sockets return immediately. The system records the peer's address. accept(), and listen() are not used with datagram sockets. While a datagram socket is connected, errors from previous send() calls can be returned asynchronously. These errors can be reported on subsequent operations on the socket, or an option of getsockopt(), SO_ERROR, can be used to interrogate the error status. Example 2-4 shows how to send an Internet call by creating a socket, binding a name to the socket, and sending the message to the socket. Example 2-4 Sending an Internet Domain Datagram
Example 2-5 shows how to read an Internet call by creating a socket, binding a name to the socket, and then reading from the socket. Example 2-5 Reading Internet Domain Datagrams
Input/Output MultiplexingRequests can be multiplexed among multiple sockets or files. Use the select() call to do this: The first argument of select() is the number of file descriptors in the lists pointed to by the next three arguments. The second, third, and fourth arguments of select() are pointers to three sets of file descriptors: a set of descriptors to read on, a set to write on, and a set on which exception conditions are accepted. Out-of-band data is the only exceptional condition. Any of these pointers can be a properly cast null. Each set is a structure containing an array of long integer bit masks. The size of the array is set by FD_SETSIZE (defined in select.h). The array is long enough to hold one bit for each FD_SETSIZE file descriptor. The macros FD_SET(fd, &mask) and FD_CLR(fd, &mask) add and delete, respectively, the file descriptor fd in the set mask. The set should be zeroed before use, and the macro FD_ZERO(&mask) clears the set mask. The fifth argument of select() allows a time-out value to be specified. If the timeout pointer is NULL, select() blocks until a descriptor is selectable, or until a signal is received. If the fields in timeout are set to 0, select() polls and returns immediately. select() normally returns the number of file descriptors selected. select() returns a 0 if the time-out has expired. select() returns -1 for an error or interrupt with the error number in errno and the file descriptor masks unchanged. For a successful return, the three sets indicate which file descriptors are ready to be read from, written to, or have exceptional conditions pending. You should test the status of a file descriptor in a select mask with the FD_ISSET(fd, &mask) macro. It returns a nonzero value if fd is in the set mask, and 0 if it is not. Use select() followed by a FD_ISSET(fd, &mask) macro on the read set to check for queued connect requests on a socket. Example 2-6 shows how to select on a "listening" socket for readability to determine when a new connection can be picked up with a call to accept(). The program accepts connection requests, reads data, and disconnects on a single socket. Example 2-6 Using select() to Check for Pending Connections
In previous versions of the select() routine, its arguments were pointers to integers instead of pointers to fd_sets. This style of call still works if the number of file descriptors is smaller than the number of bits in an integer. select() provides a synchronous multiplexing scheme. The SIGIO and SIGURG signals described in "Advanced Topics" provide asynchronous notification of output completion, input availability, and exceptional conditions. Standard RoutinesYou might need to locate and construct network addresses. This section describes the routines that manipulate network addresses. Unless otherwise stated, functions presented in this section apply only to the Internet domain. Locating a service on a remote host requires many levels of mapping before client and server communicate. A service has a name for human use. The service and host names must be translated to network addresses. Finally, the address is used to locate and route to the host. The specifics of the mappings can vary between network architectures. Preferably, a network does not require that hosts be named, thus protecting the identity of their physical locations. It is more flexible to discover the location of the host when it is addressed. Standard routines map host names to network addresses, network names to network numbers, protocol names to protocol numbers, and service names to port numbers, and the appropriate protocol to use in communicating with the server process. The file netdb.h must be included when using any of these routines. Host NamesAn Internet host-name-to-address mapping is represented by the hostent structure: gethostbyname() maps an Internet host name to a hostent structure, gethostbyaddr() maps an Internet host address to a hostent structure, and inet_ntoa() maps an Internet host address to a displayable string. The routines return a hostent structure containing the name of the host, its aliases, the address type (address family), and a NULL-terminated list of variable length addresses. The list of addresses is required because a host can have many addresses. The h_addr definition is for backward compatibility, and is the first address in the list of addresses in the hostent structure. Network NamesThe routines to map network names to numbers, and back return a netent structure: getnetbyname(), getnetbyaddr(), and getnetent() are the network counterparts to the host routines described above. Protocol NamesThe protoent structure defines the protocol-name mapping used with getprotobyname(), getprotobynumber(), and getprotoent():
In the UNIX domain, no protocol database exists. Service NamesAn Internet domain service resides at a specific, well-known port and uses a particular protocol. A service-name-to-port-number mapping is described by the servent structure:
getservbyname() maps service names and, optionally, a qualifying protocol to a servent structure. The call:
returns the service specification of a telnet server using any protocol. The call:
returns the telnet server that uses the TCP protocol. getservbyport() and getservent() are also provided. getservbyport() has an interface similar to that of getservbyname(); an optional protocol name can be specified to qualify lookups. Other RoutinesIn addition to address-related database routines, there are several other routines that simplify manipulating names and addresses. Table 2-3 summarizes the routines for manipulating variable-length byte strings and byte-swapping network addresses and values. Table 2-3 Runtime Library Routines
The byte-swapping routines are provided because the operating system expects addresses to be supplied in network order. On some architectures, the host byte ordering is different from network byte order, so programs must sometimes byte-swap values. Routines that return network addresses do so in network order. Byte-swapping problems occur only when interpreting network addresses. For example, the following code formats a TCP or UDP port:
On certain machines, where these routines are not needed, they are defined as null macros. Client-Server ProgramsThe most common form of distributed application is the client/server model. In this scheme, client processes request services from a server process. An alternate scheme is a service server that can eliminate dormant server processes. An example is inetd, the Internet service daemon. inetd listens at a variety of ports, determined at start up by reading a configuration file. When a connection is requested on an inetd serviced port, inetd spawns the appropriate server to serve the client. Clients are unaware that an intermediary has played any part in the connection. inetd is described in more detail in "inetd Daemon". ServersMost servers are accessed at well-known Internet port numbers or UNIX domain names. Example 2-7 illustrates the main loop of a remote-login server. Example 2-7 Remote Login ServerExample 2-8 shows how the server gets its service definition. Example 2-8 Remote Login Server: Step 1
The result from getservbyname() is used later to define the Internet port at which the program listens for service requests. Some standard port numbers are in /usr/include/netinet/in.h. Example 2-9 shows how the server dissociates from the controlling terminal of its invoker in the non-DEBUG mode of operation. Example 2-9 Dissociating From the Controlling Terminal
This prevents the server from receiving signals from the process group of the controlling terminal. After a server has dissociated itself, it cannot send reports of errors to a terminal and must log errors with syslog(). A server next creates a socket and listens for service requests. bind() ensures that the server listens at the expected location. (The remote login server listens at a restricted port number, so it runs as super-user.) Example 2-10 illustrates the main body of the loop. Example 2-10 Remote Login Server: Main Body
accept() blocks messages until a client requests service. accept() returns a failure indication if it is interrupted by a signal, such as SIGCHLD. The return value from accept() is checked and an error is logged with syslog() if an error has occurred. The server then forks a child process and invokes the main body of the remote login protocol processing. The socket used by the parent to queue connection requests is closed in the child. The socket created by accept() is closed in the parent. The address of the client is passed to doit() for authenticating clients. ClientsThis section describes the steps taken by the client remote login process. As in the server, the first step is to locate the service definition for a remote login:
Next, the destination host is looked up with a gethostbyname() call:
The next step is to connect to the server at the requested host and start the remote login protocol. The address buffer is cleared and filled with the Internet address of the foreign host and the port number at which the login server listens:
A socket is created, and a connection initiated. connect() implicitly does a bind(), since s is unbound.
Connectionless ServersSome services use datagram sockets. The rwho service provides status information on hosts connected to a local area network. (Avoid running in.rwhod because it causes heavy network traffic.) This service requires the ability to broadcast information to all hosts connected to a particular network. It is an example of datagram socket use. A user on a host running the rwho server can get the current status of another host with ruptime. Typical output is illustrated in Example 2-11. Example 2-11 Output of ruptime Program
Status information is periodically broadcast by the rwho server processes on each host. The server process also receives the status information and updates a database. This database is interpreted for the status of each host. Servers operate autonomously, coupled only by the local network and its broadcast capabilities. Use of broadcast is fairly inefficient because a lot of net traffic is generated. Unless the service is used widely and frequently, the expense of periodic broadcasts outweighs the simplicity. Example 2-12 shows a simplified version of the rwho server. It performs two tasks: receives status information broadcast by other hosts on the network and supplies the status of its host. The first task is done in the main loop of the program: Packets received at the rwho port are checked to be sure they were sent by another rwho server process, and are stamped with the arrival time. They then update a file with the status of the host. When a host has not been heard from for an extended time, the database routines assume the host is down and logs it. This application is prone to error, as a server might be down while a host is up. Example 2-12 rwho Server
The second server task is to supply the status of its host. This requires periodically acquiring system status information, packaging it in a message, and broadcasting it on the local network for other rwho servers to hear. This task is run by a timer and triggered with a signal. Locating the system status information is involved but uninteresting. Status information is broadcast on the local network. For networks that do not support broadcast, use another scheme. It is important that software operating in a distributed environment not have any site-dependent information compiled into it. This would require a separate copy of the server at each host and make maintenance a severe problem. The system isolates host-specific data from applications by providing function calls that return the required data. (For example, uname() returns the host's official name.) The SIOCGIFCONF ioctl() call lets you find the networks to which a host is directly connected. A local network broadcasting mechanism has been implemented at the socket level. Combining these two features lets a process broadcast on any directly connected local network that supports broadcasting in a site-independent manner. This solves the problem of deciding how to propagate status with rwho, or more generally in broadcasting. Such status is broadcast to connected networks at the socket level, where the connected networks have been obtained through the appropriate ioctl() calls. "Broadcasting and Determining Network Configuration" details the specifics of broadcasting. Advanced TopicsFor most programmers, the mechanisms already described are enough to build distributed applications. Others need some of the additional features in this section. Out-of-Band DataThe stream socket abstraction includes out-of-band data. Out-of-band data is a logically independent transmission channel between a pair of connected stream sockets. Out-of-band data is delivered independent of normal data. The out-of-band data facilities must support the reliable delivery of at least one out-of-band message at a time. This message can contain at least one byte of data, and at least one message can be pending delivery at any time. For communications protocols that support only in-band signaling (that is, urgent data is delivered in sequence with normal data), the message is extracted from the normal data stream and stored separately. This lets users choose between receiving the urgent data in order and receiving it out of sequence, without having to buffer the intervening data. You can peek (with MSG_PEEK) at out-of-band data. If the socket has a process group, a SIGURG signal is generated when the protocol is notified of its existence. A process can set the process group or process id to be informed by SIGURG with the appropriate fcntl() call, as described in "Interrupt-Driven Socket I/O" for SIGIO. If multiple sockets have out-of-band data waiting delivery, a select() call for exceptional conditions can be used to determine the sockets with such data pending. A logical mark is placed in the data stream at the point at which the out-of-band data was sent. The remote login and remote shell applications use this facility to propagate signals between client and server processes. When a signal is received, all data up to the mark in the data stream is discarded. To send an out-of-band message, the MSG_OOB flag is applied to send() or sendto(). To receive out-of-band data, specify MSG_OOB to recvfrom() or recv() (unless out-of-band data is taken in line, in which case the MSG_OOB flag is not needed). The SIOCATMARK ioctl tells whether the read pointer currently points at the mark in the data stream:
If yes is 1 on return, the next read returns data after the mark. Otherwise, assuming out-of-band data has arrived, the next read provides data sent by the client before sending the out-of-band signal. The routine in the remote login process that flushes output on receipt of an interrupt or quit signal is shown in Example 2-13. This code reads the normal data up to the mark (to discard it), then reads the out-of-band byte. A process can also read or peek at the out-of-band data without first reading up to the mark. This is more difficult when the underlying protocol delivers the urgent data in-band with the normal data, and only sends notification of its presence ahead of time (for example, TCP, the protocol used to provide socket streams in the Internet domain). With such protocols, the out-of-band byte might not yet have arrived when a recv() is done with the MSG_OOB flag. In that case, the call returns the error of EWOULDBLOCK. Also, there might be enough in-band data in the input buffer that normal flow control prevents the peer from sending the urgent data until the buffer is cleared. The process must then read enough of the queued data before the urgent data can be delivered. Example 2-13 Flushing Terminal I/O on Receipt of Out-of-Band Data
There is also a facility to retain the position of urgent in-line data in the socket stream. This is available as a socket-level option, SO_OOBINLINE. See the getsockopt(3N) manpage for usage. With this option, the position of urgent data (the mark) is retained, but the urgent data immediately follows the mark in the normal data stream returned without the MSG_OOB flag. Reception of multiple urgent indications causes the mark to move, but no out-of-band data are lost. Nonblocking SocketsSome applications require sockets that do not block. For example, requests that cannot complete immediately and would cause the process to be suspended (awaiting completion) are not executed. An error code would be returned. After a socket is created and any connection to another socket is made, it can be made nonblocking by issuing a fcntl() call, as shown in Example 2-14. Example 2-14 Set Nonblocking Socket
When doing I/O on a nonblocking socket, check for the error EWOULDBLOCK (in errno.h), which occurs when an operation would normally block. accept(), connect(), send(), recv(), read(), and write() can all return EWOULDBLOCK. If an operation such as a send() cannot be done in its entirety, but partial writes work (such as when using a stream socket), the data that can be sent immediately are processed, and the return value is the amount actually sent. Asynchronous Socket I/OAsynchronous communication between processes is required in applications that handle multiple requests simultaneously. Asynchronous sockets must be Example 2-15 Making a Socket Asynchronous
After sockets are initialized, connected, and made asynchronous, communication is similar to reading and writing a file asynchronously. A send(), write(), recv(), or read() initiates a data transfer. A data transfer is completed by a signal-driven I/O routine, described in the next section. Interrupt-Driven Socket I/OThe SIGIO signal notifies a process when a socket (actually any file descriptor) has finished a data transfer. The steps in using SIGIO are:
Example 2-16 shows some sample code to allow a given process to receive information on pending requests as they occur for a socket. With the addition of a handler for SIGURG(), this code can also be used to prepare for receipt of SIGURG signals. Example 2-16 Asynchronous Notification of I/O Requests
Signals and Process Group IDFor SIGURG and SIGIO, each socket has a process number and a process group ID. These values are initialized to zero, but can be redefined at a later time with the F_SETOWN fcntl(), as in the previous example. A positive third argument to fcntl() sets the socket's process ID. A negative third argument to fcntl() sets the socket's process group ID. The only allowed recipient of SIGURG and SIGIO signals is the calling process. A similar fcntl(), F_GETOWN, returns the process number of a socket. Reception of SIGURG and SIGIO can also be enabled by using ioctl() to assign the socket to the user's process group:
Another signal that is useful in server processes is SIGCHLD. This signal is delivered to a process when any child process changes state. Normally, servers use the signal to "reap" child processes that have exited without explicitly awaiting their termination or periodically polling for exit status. For example, the remote login server loop shown previously can be augmented as shown in Example 2-17. Example 2-17 SIGCHLD Signal
If the parent server process fails to reap its children, zombie processes result. Selecting Specific ProtocolsIf the third argument of the socket() call is 0, socket() selects a default protocol to use with the returned socket of the type requested. The default protocol is usually correct, and alternate choices are not usually available. When using "raw" sockets to communicate directly with lower-level protocols or hardware interfaces, it may be important for the protocol argument to set up de-multiplexing. For example, raw sockets in the Internet domain can be used to implement a new protocol on IP, and the socket receives packets only for the protocol specified. To obtain a particular protocol, determine the protocol number as defined in the protocol domain. For the Internet domain, use one of the library routines discussed in "Standard Routines", such as getprotobyname():
This results in a socket s using a stream-based connection, but with protocol type of Address BindingTCP and UDP use a 4-tuple of local IP address, local port number, foreign IP address, and foreign port number to do their addressing. TCP requires these 4-tuples to be unique. UDP does not. It is unrealistic to expect user programs to always know proper values to use for the local address and local port, since a host can reside on multiple networks and the set of allocated port numbers is not directly accessible to a user. To avoid these problems, you can leave parts of the address unspecified and let the system assign the parts appropriately when needed. Various portions of these tuples may be specified by various parts of the sockets API.
A call to accept() retrieves connection information from a foreign client, so it causes the local address and port to be specified to the system (even though the caller of accept() didn't specify anything), and the foreign address and port to be returned. A call to listen() can cause a local port to be chosen. If no explicit bind() has been done to assign local information, listen() causes an ephemeral port number to be assigned. A service that resides at a particular port, but which does not care what local address is chosen, can bind() itself to its port and leave the local address unspecified (set to INADDR_ANY, a constant defined in <netinet/in.h>). If the local port need not be fixed, a call to listen() causes a port to be chosen. Specifying an address of INADDR_ANY or a port number of 0 is known as wildcarding. The wildcard address simplifies local address binding in the Internet domain. The sample code below binds a specific port number, MYPORT, to a socket, and leaves the local address unspecified. Example 2-18 Bind Port Number to Socket
Each network interface on a host typically has a unique IP address. Sockets with wildcard local addresses can receive messages directed to the specified port number and sent to any of the possible addresses assigned to a host. For example, if a host has two interfaces with addresses 128.32.0.4 and 10.0.0.78, and a socket is bound as in Example 2-18, the process can accept connection requests addressed to 128.32.0.4 or 10.0.0.78. To allow only hosts on a specific network to connect to it, a server binds the address of the interface on the appropriate network. Similarly, a local port number can be left unspecified (specified as 0), in which case the system selects a port number. For example, to bind a specific local address to a socket, but to leave the local port number unspecified:
The system uses two criteria to select the local port number:
The port number and IP address of the client is found through either accept() (the from result) or getpeername(). In certain cases, the algorithm used by the system to select port numbers is unsuitable for an application. This is because associations are created in a two-step process. For example, the Internet file transfer protocol specifies that data connections must always originate from the same local port. However, duplicate associations are avoided by connecting to different foreign ports. In this situation, the system would disallow binding the same local address and port number to a socket if a previous data connection's socket still existed. To override the default port selection algorithm, you must perform an option call before address binding:
With this call, local addresses already in use can be bound. This does not violate the uniqueness requirement, because the system still verifies at connect time that any other sockets with the same local address and port do not have the same foreign address and port. If the association already exists, the error EADDRINUSE is returned. Broadcasting and Determining Network ConfigurationMessages sent by datagram sockets can be broadcast to reach all of the hosts on an attached network. The network must support broadcast; the system provides no simulation of broadcast in software. Broadcast messages can place a high load on a network since they force every host on the network to service them. Broadcasting is usually used for either of two reasons: to find a resource on a local network without having its address, or functions like routing require that information be sent to all accessible neighbors. To send a broadcast message, create an Internet datagram socket:
and bind a port number to the socket:
The datagram can be broadcast on only one network by sending to the network's broadcast address. A datagram can also be broadcast on all attached networks by sending to the special address INADDR_BROADCAST, defined in netinet/in.h. The system provides a mechanism to determine a number of pieces of information (including the IP address and broadcast address) about the network interfaces on the system. The SIOCGIFCONF ioctl() call returns the interface configuration of a host in a single ifconf structure. This structure contains an array of ifreq structures, one for each address domain supported by each network interface to which the host is connected. Example 2-19 shows these structures defined in net/if.h. Example 2-19 net/if.h Header File
The call that obtains the interface configuration is:
After this call, buf contains an array of ifreq structures, one for each network to which the host is connected. These structures are ordered first by interface name, then by supported address families. ifc.ifc_len is set to the number of bytes used by the ifreq structures. Each structure has a set of interface flags that tell whether the corresponding network is up or down, point-to-point or broadcast, and so on. Example 2-20 shows the SIOCGIFFLAGS ioctl() returning these flags for an interface specified by an ifreq structure. Example 2-20 Obtaining Interface Flags
Example 2-21 shows the broadcast of an interface can be obtained with the SIOGGIFBRDADDR ioctl(). Example 2-21 Broadcast Address of an Interface
The SIOGGIFBRDADDR ioctl() can also be used to get the destination address of a point-to-point interface. After the interface broadcast address is obtained, transmit the broadcast datagram with sendto():
Use one sendto() for each interface to which the host is connected that supports the broadcast or point-to-point addressing. Zero Copy and Checksum OffloadIn Solaris 2.6, the TCP/IP protocol stack has been enhanced to support two new features: zero copy and TCP checksum offload.
Note - Although zero copy and checksum offloading are functionally independent of one another, they have to work together to obtain the optimal performance. Checksum offloading requires hardware support from the network interface and, without this hardware support, zero copy is not enabled. Zero copy requires that the applications supply page-aligned buffers before VM page remapping can be applied. Applications should use large, circular buffers on the transmit side to avoid expensive copy-on-write faults. A typical buffer allocation is sixteen 8k buffers. Socket OptionsYou can set and get several options on sockets through setsockopt() and getsockopt(); for example by changing the send or receive buffer space. The general forms of the calls are:
and
Note - In some cases, such as setting the buffer sizes, these are only hints to the operating system. The operating system reserves the right to adjust the values appropriately. Table 2-4 shows the arguments of the calls. Table 2-4 setsockopt() and getsockopt() Arguments
For getsockopt(), optlen is a value-result argument, initially set to the size of the storage area pointed to by optval and set on return to the length of storage used. It is sometimes useful to determine the type (for example, stream or datagram) of an existing socket. Programs invoked by inetd can do this by using the SO_TYPE socket option and the getsockopt() call:
After getsockopt(), type is set to the value of the socket type, as defined in sys/socket.h. For a datagram socket, type would be inetd DaemonOne of the daemons provided with the system is inetd. It is invoked at start-up time, and gets the services for which it listens from the /etc/inetd.conf file. The daemon creates one socket for each service listed in /etc/inetd.conf, binding the appropriate port number to each socket. See the inetd(1M) man page for details.
inetd polls each socket, waiting for a connection request to the service corresponding to that socket. For The primary benefit of inetd is that services that are not in use are not taking up machine resources. A secondary benefit is that inetd does most of the work to establish a connection. The server started by inetd has the socket connected to its client on file descriptors 0 and 1, and can immediately read(), write(), send(), or recv(). Servers can use buffered I/O as provided by the stdio conventions, as long as they use fflush() when appropriate. getpeername() returns the address of the peer (process) connected to a socket; it is useful in servers started by inetd. For example, to log the Internet address in decimal dot notation (such as 128.32.0.4, which is conventional for representing an IP address of a client), an inetd server could use the following:
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||