BSD Sockets Interface Programmer’s Guide Edition 6 B2355-90136 HP 9000 Networking E0497 Printed in: United States © Copyright 1997 Hewlett-Packard Company.
Legal Notices The information in this document is subject to change without notice. Hewlett-Packard makes no warranty of any kind with regard to this manual, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. Hewlett-Packard shall not be held liable for errors contained herein or direct, indirect, special, incidental or consequential damages in connection with the furnishing, performance, or use of this material. Warranty.
©copyright 1980, 1984, 1986 Novell, Inc. ©copyright 1986-1992 Sun Microsystems, Inc. ©copyright 1985-86, 1988 Massachusetts Institute of Technology. ©copyright 1989-93 The Open Software Foundation, Inc. ©copyright 1986 Digital Equipment Corporation. ©copyright 1990 Motorola, Inc.
Contents 1. BSD Sockets Concepts Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 Key Terms and Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17 How You Can Use BSD Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20 The Client-Server Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21 Creating a Connection: the Client-Server Model . . . . . . . . . . . . . .
Contents Example Using Internet Stream Sockets . . . . . . . . . . . . . . . . . . . . . . . . 48 3. Advanced Topics for Stream Sockets Socket Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Getting and Setting Socket Options. . . . . . . . . . . . . . . . . . . . . . . . . . . SO_REUSEADDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . SO_KEEPALIVE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Contents 4. Using Internet Datagram Sockets Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .86 Preparing Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .88 Declaring Socket Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .88 Getting the Remote Host's Network Address . . . . . . . . . . . . . . . . . . . .89 Getting the Port Address for the Desired Service . . . . . . . . . . . . . . . .
Contents Using Broadcast Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 6. Using UNIX Domain Stream Sockets Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124 Preparing Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Declaring Socket Address Variables . . . . . . . . . . . . . . . . . . . . . . . . . 126 Writing the Server Process . . . . . . . . . . . . . . . . . . . . . .
Contents Sending and Receiving Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155 Sending Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .155 Receiving Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .156 Closing a Socket. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159 Example Using UNIX Domain Datagram Sockets . . . . . . . . . . . . . . . .160 8.
Contents 10
Printing History The manual printing date and part number indicate its current edition. The printing date will change when a new edition is printed. Minor changes may be made at reprint without changing the printing date. the manual part number will change when extensive changes are made. Manual updates may be issued between editions to correct errors or document product changes. To ensure that you receive the updated or new editions, you should subscribe to the appropriate product support service.
Preface This guide describes HP's BSD Sockets. BSD Sockets is a set of programming development tools for interprocess communication. HP's implementation of BSD Sockets is a full set of sockets from the networking services originally developed by the University of California at Berkeley (UCB). The BSD Sockets Interface Programmer's Guide is the primary reference for programmers who write or maintain BSD Sockets applications on HP 9000 computers.
Chapter 5 Advanced Topics for Internet Datagram Sockets includes information about default socket address, synchronous I/O multiplexing with select, sending and receiving IP multicast datagrams, and broadcast addresses. Chapter 6 Using UNIX Domain Stream Sockets describes the steps involved in creating a UNIX Domain stream socket connection between two processes executing on the same node.
1 BSD Sockets Concepts The BSD Sockets facility allows you to create distributed applications that pass data between programs (on the same computer or on separate computers on the network) without requiring an understanding of the 15
BSD Sockets Concepts many layers of networking protocols. This is accomplished by using a set of system calls. These system calls allow you to create communication endpoints called sockets and transfer data between them. NOTE BSD Sockets is a program development tool. Before you attempt to use BSD Sockets, you may need to familiarize yourself with the C programming language and the HP-UX operating system.
BSD Sockets Concepts Introduction Introduction This guide describes the steps involved in establishing and using BSD Sockets connections. It also describes the protocols you must use and how the BSD Sockets system calls interact. The details of each system call are described in the corresponding man pages. Key Terms and Concepts For a basic understanding of BSD Sockets and its general model, you should review the following terms and definitions.
BSD Sockets Concepts Introduction binding Before a socket can be accessed across the network, it must be bound to an address. Binding associates a socket address with a socket and makes the socket accessible to other sockets on the network. Once a socket address is bound, other sockets can connect to the socket and send data to or receive data from it. channel Communication path created by establishing a connection between sockets.
BSD Sockets Concepts Introduction socket address For the internet address family (AF_INET), the socket address consists of the internet address, port address and address family of a socket. The internet and port address combination allows the network to locate a socket. For UNIX Domain (AF_UNIX), the socket address is the directory pathname bound to the socket. socket descriptor A socket descriptor is an HP-UX file descriptor that references a socket instead of an ordinary file.
BSD Sockets Concepts How You Can Use BSD Sockets How You Can Use BSD Sockets The best example of how BSD Sockets can be used is the Internet Services. These services use BSD Sockets to communicate between remote hosts. Using the BSD Sockets facility, you can write your own distributed application programs to do a variety of tasks. For example, you can write distributed application programs to: • Access a remote database. • Access multiple computers at one time. • Spread tasks across several hosts.
BSD Sockets Concepts The Client-Server Model The Client-Server Model Typical BSD Sockets applications consist of two separate application level processes; one process (the client) requests a connection and the other process (the server) accepts it. The server process creates a socket, binds an address to it, and sets up a mechanism (called a listen queue) for receiving connection requests. The client process creates a socket and requests a connection to the server process.
BSD Sockets Concepts The Client-Server Model Figure 1-1 Client-Server in a Pre-Connection State 22 Chapter 1
BSD Sockets Concepts The Client-Server Model Figure 1-2 Client-Server at Time of Connection Request Chapter 1 23
BSD Sockets Concepts The Client-Server Model Figure 1-3 Client-Server When Connection is Established 24 Chapter 1
BSD Sockets Concepts BSD Sockets Library Routines BSD Sockets Library Routines The library routines and system calls that you need to implement a BSD Sockets application are described throughout the guide. In addition, a complete list of all these routines and system calls is provided in the “Summary Tables for Library and System Calls” section of chapter 8, “Programming Hints.” The library routines are in the common “c” library named libc.sl.
BSD Sockets Concepts BSD Sockets Library Routines 26 Chapter 1
2 Using Internet Stream Sockets 27
Using Internet Stream Sockets NOTE Release 10.10 and later releases support two variations of sockets behavior: classic HP-UX sockets and X/Open sockets. By default, users receive classic HP-UX sockets. To use X/Open sockets, users must make an addition to their make files by including the “-l xnet” argument with the “c89” or “cc” utilities.
Using Internet Stream Sockets Overview Overview Internet TCP stream sockets provide bidirectional, reliable, sequenced and unduplicated flow of data without record boundaries. The following table lists the steps involved in creating and terminating a BSD Sockets connection using stream sockets.
Using Internet Stream Sockets Overview Each of these steps or activities is described in more detail in the following sections. The description of each activity specifies a system call and includes: • What happens when the system call is used. • When to make the call. • What the parameters do. • How the call interacts with other BSD Sockets system calls. • Where to find details on the system call. The stream socket program examples are at the end of these descriptive sections.
Using Internet Stream Sockets Preparing Address Variables Preparing Address Variables Before you create a connection, establish the correct variables and collect the information that you need to request a connection. Your server process needs to: • Declare socket address variables. • Assign a wildcard address. • Get the port address of the service that you want to provide. Your client process needs to: • Declare socket address variables. • Get the remote host's internet address.
Using Internet Stream Sockets Preparing Address Variables Field Description short sin_family Specifies the address family and should always be set to AF_INET. u_short sin_port Specifies the port address. Assign this field when you bind the port address for the socket or when you get a port address for a specific service. struct inaddr sin_addr Specifies the internet address. Assign this field when you get the internet address for the remote host.
Using Internet Stream Sockets Preparing Address Variables #include struct hostent *hp; /* pointer to host info for remote host */ ... peeraddr.sin_family = AF_INET; hp = gethostbyname (argv[1]); peeraddr_in.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr; The argv[1] parameter is the host name specified in the client program command line. Refer to the gethostent(3n) man page for more information on gethostbyname.
Using Internet Stream Sockets Preparing Address Variables #include struct servent *sp; /* pointer to service info */ ... sp = getservbyname (“example”, “tcp”); peeraddr.sin_port = sp->s_port; When to Get the Server's Socket Address The server process needs to get the socket address before binding the listen socket. The client process needs to get the socket address before the client executes a connection request. Refer to the getservent(3n) man page for more information on getservbyname.
Using Internet Stream Sockets Writing the Server Process Writing the Server Process This section explains the calls your server process must make to connect with and serve a client process. Creating a Socket The server process must call socket to create a communication endpoint. socket and its parameters are described in the following table. Include files: #include #include
Using Internet Stream Sockets Writing the Server Process When to Create Sockets The server process should create a socket before any other BSD Sockets system calls. Refer to the socket(2) man page for more information on socket. Binding a Socket Address to the Server Process's Socket After your server process has created a socket, it must call bind to bind a socket address. Until an address is bound to the server socket, other processes have no way to reference it.
Using Internet Stream Sockets Writing the Server Process Example: struct sockaddr_in myaddr; ... bind (ls, &myaddr, sizeof(struct sockaddr_in)); When to Bind Socket Addresses The server process should bind the socket address after the socket is created and before any other BSD Sockets system calls. Refer to the bind(2) man page for more information on bind.
Using Internet Stream Sockets Writing the Server Process backlog is the preferred number of unaccepted incoming connections allowed at a given time. The actual number may be greater than the specified backlog. When the request is full, further connection requests are rejected. A backlog of 0 specifies only 1 pending connection can exist at any given time. SOMAXCONN is defined in . The default setting is 20.
Using Internet Stream Sockets Writing the Server Process Parameter Contents INPUT Value OUTPUT Value ls socket descriptor of local socket socket descriptor of server socket unchanged addr socket address pointer to address structure where address will be put pointer to socket address of client socket that server’s new socket is connected to addrlen length of address pointer to the size of struct sockaddr_in pointer to the actual length of address returned in addr Function result: socket desc
Using Internet Stream Sockets Writing the Client Process Writing the Client Process This section explains the calls your client process must make to connect with and be served by a server process. Creating a Socket The client process must call socket to create a communication endpoint. socket and its parameters are described in the following table. Include files: #include #include
Using Internet Stream Sockets Writing the Client Process Requesting a Connection Once the server process is listening for connection requests, the client process can request a connection with the connect call. connect and its parameters are described in the following table. Include files: #include #include #include
Using Internet Stream Sockets Writing the Client Process NOTE The client process does not get feedback that the server process has completed the accept call. As soon as the connect call returns, the client process can send data. Local internet and port addresses are bound when connect is executed if you have not already bound them yourself. These address values are chosen by the local host.
Using Internet Stream Sockets Sending and Receiving Data Sending and Receiving Data After the connect and accept calls are successfully executed, the connection is established and data can be sent and received between the two socket endpoints. Because the stream socket descriptors correspond to HP-UX file descriptors, you can use the read and write calls (in addition to recv and send) to pass data through a socket-terminated channel.
Using Internet Stream Sockets Sending and Receiving Data Parameter Description of Contents INPUT Value msg pointer to data buffer pointer to data to be sent len size of data buffer size of msg flags settings for optional flags 0 or MSG_OOB Function result: number of bytes actually sent, –1 if failure occurs. Example: count = send (s, buf, 10, 0); send blocks until the specified number of bytes have been queued to be sent, unless you are using nonblocking I/O.
Using Internet Stream Sockets Sending and Receiving Data Description of Contents INPUT Value s socket descriptor of local socket socket descriptor of socket receiving data buf pointer to data buffer pointer to buffer that is to receive data len maximum number of bytes that should be received size of data buffer flags settings for optional flags 0, MSG_OOB or MSG_PEEK Parameter Function result: number of bytes actually received, –1 if failure occurs.
Using Internet Stream Sockets Sending and Receiving Data Use the MSG_PEEK option to preview incoming data. If this option is set on a recv, any data returned remains in the socket buffer as though it had not been read yet. The next recv returns the same data. When to Receive Data The server or client process should receive data after connection is established. Refer to the recv(2) man page for more information on recv.
Using Internet Stream Sockets Closing a Socket Closing a Socket In most applications, you do not have to worry about cleaning up your sockets. When you exit your program and your process terminates, the sockets are closed for you. If you need to close a socket while your program is still running, use the close system call. For example, you may have a daemon process that uses fork to create the server process.
Using Internet Stream Sockets Example Using Internet Stream Sockets Example Using Internet Stream Sockets NOTE These programs are provided as examples only of stream socket usage and are not Hewlett-Packard supported products. These program examples demonstrate how to set up and use internet stream sockets. These sample programs are in the /usr/lib/demos/networking/socket directory. The client program is intended to run in conjunction with the server program.
Using Internet Stream Sockets Example Using Internet Stream Sockets * demonstrate many of the features of sockets, as well as good * conventions for using these features. * * This program provides a service called “example”. In order for * it to function, an entry for it needs to exist in the * /etc/services file. The port address for this service can be * any port number that is likely to be unused, such as 22375, * for example.
Using Internet Stream Sockets Example Using Internet Stream Sockets * network at once will be able to have one server * listening on all networks at once. Even when the * host is connected to only one network, this is good * practice, because it makes the server program more * portable. */ myaddr_in.sin_addr.s_addr = INADDR_ANY; /* Find the information for the “example” server * in order to get the needed port number.
Using Internet Stream Sockets Example Using Internet Stream Sockets fprintf(stderr, “%s: unable to fork daemon\n”, argv[0]); exit(1); case 0: /* The child process (daemon) comes here. */ /* Close stdin and stderr so that they will not * be kept open. Stdout is assumed to have been * redirected to some logging file, or /dev/null. * From now on, the daemon will not report any * error messages. This daemon will loop forever, * waiting for connections and forking a child * server to handle each one.
Using Internet Stream Sockets Example Using Internet Stream Sockets } /* * S E R V E R * * This is the actual server routine that the daemon forks * to handle each individual connection. Its purpose is * to receive the request packets from the remote client, * process them, and return the results to the client. * It will also write some logging information to stdout. * */ server() { int reqcnt = 0; /* keeps count of number of requests */ char buf[10]; /* This example uses 10 byte messages.
Using Internet Stream Sockets Example Using Internet Stream Sockets exit(1); } /* Go into a loop, receiving requests from the * remote client. After the client has sent the * last request, it will do a shutdown for sending, * which causes an end-of-file condition to appear * on this end of the connection. After all of the * client’s requests have been received, the next * recv call will return zero bytes, signalling an * end-of-file condition.
Using Internet Stream Sockets Example Using Internet Stream Sockets /* The port number must be converted first to * host byte order before printing. On most hosts, * this is not necessary, but the ntohs() call is * included here so this program could easily * be ported to a host that does require it. */ printf(”Completed %s port %u, %d requests, at %s\n”, hostname, ntohs(peeraddr_in.sin_port), reqcnt, ctime(&timevar)); } /* * * * * * * * * * * * * * * * * */ C L I E N T .
Using Internet Stream Sockets Example Using Internet Stream Sockets int argc; char *argv[]; { int addrlen, i, j; /* This example uses 10 byte messages. */ char buf[10]; if (argc != 2) { fprintf(stderr, “Usage:%s \n” argv[0]; exit(1); } /* clear out address structures */ memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in)); memset ((char *)&peeraddr_in, 0, sizeof(struct sockaddr_in)); /* Set up the peer address to which we will connect. */ peeraddr_in.
Using Internet Stream Sockets Example Using Internet Stream Sockets * addrlen needs to be passed in as a pointer, * because getsockname returns the actual length * of the address. */ addrlen = sizeof(struct sockaddr_in); if (getsockname(s, &myaddr_in, &addrlen) == -1) { perror(argv[0]); fprintf(stderr, “%s: unable to read socket address\n”, argv[0]); exit(1); } /* Print out a startup message for the user. */ time(&timevar); /* The port number must be converted first to * host byte order before printing.
Using Internet Stream Sockets Example Using Internet Stream Sockets if (shutdown(s, 1) == -1) { perror(argv[0]); fprintf(stderr, “%s: unable to shutdown socket\n”,argv[0]); exit(1); } /* Start receiving all the replys from the server. * This loop will terminate when the recv returns * zero, which is an end-of-file condition. This * will happen after the server has sent all of its * replies, and closed its end of the connection.
Using Internet Stream Sockets Example Using Internet Stream Sockets 58 Chapter 2
3 Advanced Topics for Stream Sockets 59
Advanced Topics for Stream Sockets This chapter explains the following: • Socket options. • Synchronous I/O multiplexing with select. • Sending and receiving data asynchronously. • Nonblocking I/O. • Using shutdown. • Using read and write to make stream sockets transparent. • Sending and receiving out of band data.
Advanced Topics for Stream Sockets Socket Options Socket Options The operation of sockets is controlled by socket level options.
Advanced Topics for Stream Sockets Socket Options • SO_SNDTIMEO • SO_RCVTIMEO • SO_BROADCAST • SO_REUSEPORT In addition, the SO_DEBUG option is supported for compatibility only; it has no functionality. Options for protocol levels are described in the individual protocol manual pages, such as tcp(7p), udp(7p), and ip(7p). The next section describes how to get the current value of a socket option and to set socket options, followed by a description of each available option.
Advanced Topics for Stream Sockets Socket Options Parameter Contents INPUT Value OUTPUT Value s socket descriptor socket descriptor for which option values are to be returned unchanged level protocol level SOL_SOCKET unchanged optname name of option supported option name unchanged optval pointer to current value of option pointer to buffer where option’s current value is to be returned pointer to buffer that contains current option value optlen pointer to length of optval pointer to m
Advanced Topics for Stream Sockets Socket Options • SO_RCVTIMEO The following socket options toggle socket behavior. optval is an integer containing a boolean flag for the behavior (1 = on, 0 = off): • SO_KEEPALIVE • SO_DEBUG • SO_DONTROUTE • SO_USELOOPBACK • SO_REUSEADDR • SO_OOBINLINE • SO_REUSEPORT The SO_LINGER option is a combination. It sets a linger value, and also toggles linger behavior on and off. In previous releases SO_DONTLINGER was supported.
Advanced Topics for Stream Sockets Socket Options Parameter Description of Contents INPUT Value optname name of option supported option name optval pointer to option input value Must be at least size of (int). Holds either value to be set or boolean flag optlen length of optval size of optval Function result: 0 if setsockopt is successful, –1 if failure occurs. Example: See the description of the SO_REUSEADDR option for an example.
Advanced Topics for Stream Sockets Socket Options Network Daemon Server Listening at Port 2000. When the network daemon accepts a connection request, the accepted socket will bind to port 2000 and to the address where the daemon is running (e.g. 192.6.250.100). If you executed netstat an, the output would resemble: Active connections (including servers) Proto Recv-Q Send-Q Local Address Foreign Address (state) tcp 0 0 192.6.250.100.2000 192.6.250.101.4000 ESTABLISHED tcp 0 0 *.2000 *.
Advanced Topics for Stream Sockets Socket Options SO_DONTROUTE This option is AF_INET socket-specific. SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. Instead, messages are directed to the appropriate network interface according to the network portion of the destination address. SO_SNDBUF SO_SNDBUF changes the send socket buffer size.
Advanced Topics for Stream Sockets Socket Options Table 3-1 Summary Information for Changing Socket Buffer Size SocketType (Protocol) stream (TCP) When Buffer Size Increase Allowed at any time When Buffer Size Decrease Allowed only prior to establishing a connection Maximum Buffer Size 262144 bytes SO_LINGER SO_LINGER controls the actions taken when a close is executed on a socket that has unsent data. This option can be cleared by toggling. The default is off.
Advanced Topics for Stream Sockets Socket Options Table 3-2 Summary of Linger Options on Close Socket Option Option Set Linger Interval Graceful Close SO_LINGER off don't care x SO_LINGER on zero SO_LINGER on nonzero Hard Close Wait for Close x x x Does Not Wait for Close x x SO_USELOOPBACK This option is not applicable to UNIX Domain sockets. SO_USELOOPBACK directs the network layer (IP) of networking code to use the local loopback address when sending data from this socket.
Advanced Topics for Stream Sockets Socket Options SO_RCVLOWAT This option allows the user to set or fetch the low water mark for the socket's receive socket buffer. At present, this option is not used. It is supported in anticipation of future use. SO_SNDTIMEO This option allows the user to set or fetch the timeout value for a socket's send socket buffer.At present, this option is not used. It is supported in anticipation of future use.
Advanced Topics for Stream Sockets Socket Options are bound to the port. All processes that share the port must specify this option. For more information on using this option, see “Sending and Receiving IP Multicast Datagrams,” in Chapter 5.
Advanced Topics for Stream Sockets Synchronous I/O Multiplexing with Select Synchronous I/O Multiplexing with Select The select system call can be used with sockets to provide a synchronous multiplexing mechanism. The system call has several parameters which govern its behavior. If you specify a zero pointer for the timeout parameter, select will block until one or more of the specified socket descriptors is ready.
Advanced Topics for Stream Sockets Synchronous I/O Multiplexing with Select The following example illustrates the select system call. Since it is possible for a process to have more than 32 open file descriptors, the bit masks used by select are interpreted as arrays of integers. The header file sys/types.h contains some useful macros to be used with the select() system call, some of which are reproduced below. /* * These macros are used with select().
Advanced Topics for Stream Sockets Synchronous I/O Multiplexing with Select exit(1); } if (FD_ISSET(s, &read_mask)) do_read(s); /* something to read on socket s */ /* fall through as maybe more to do */ if (FD_ISSET(s, &write_mask)) do_write(s); /* space to write on socket s */ } } 74 Chapter 3
Advanced Topics for Stream Sockets Sending and Receiving Data Asynchronously Sending and Receiving Data Asynchronously Asynchronous sockets allow a user program to receive an SIGIO signal when the state of the socket changes. This state change can occur, for example, when new data arrives. Currently the user would have to issue a select system call in order to determine if data were available.
Advanced Topics for Stream Sockets Sending and Receiving Data Asynchronously Notification that out-of-band data has been received is also done asynchronously; see the section “Sending and Receiving Out-of-band Data” in this chapter for more details. The following example sets up an asynchronous SOCK_STREAM listen socket. This is typical of an application that needs to be notified when connection requests arrive.
Advanced Topics for Stream Sockets Nonblocking I/O Nonblocking I/O Sockets are created in blocking mode I/O by default. You can specify that a socket be put in nonblocking mode by using the ioctl system call with the FIOSNBIO request. Here is an example: #include ... ioctl(s, FIOSNBIO, &arg); arg is a pointer to int: • When int equals 0, the socket is changed to blocking mode. • When int equals 1, the socket is changed to nonblocking mode.
Advanced Topics for Stream Sockets Using Shutdown Using Shutdown When your program is done reading or writing on a particular socket connection, you can use shutdown to bring down a part of the connection. When one process uses shutdown on a socket descriptor, all other processes with the same socket descriptor are affected. shutdown causes all or part of a full-duplex connection on the specified socket to be disabled.
Advanced Topics for Stream Sockets Using Shutdown Parameter Description of Contents INPUT Value s socket descriptor socket descriptor of socket to be shut down how number that indicates the type of shutdown 0, 1 or 2 Function result: 0 if shutdown is successful, –1 if failure occurs. Example: shutdown (s, 1); When to Shut Down a Socket Optionally, after the process has sent all messages and wants to indicate that it is done sending, shut down the server or client process.
Advanced Topics for Stream Sockets Using Read and Write to Make Stream Sockets Transparent Using Read and Write to Make Stream Sockets Transparent An example application of read and write with stream sockets is to fork a command with a socket descriptor as stdout. The peer process can read input from the command. The command can be any command and does not have to know that stdout is a socket. It might use printf, which results in the use of write. Thus, the stream sockets are transparent.
Advanced Topics for Stream Sockets Sending and Receiving Out-of-band Data Sending and Receiving Out-of-band Data This option is not supported for UNIX Domain (AF_UNIX) sockets. If an abnormal condition occurs when a process is in the middle of sending a long stream of data, it is useful to be able to alert the other process with an urgent message. The TCP stream socket implementation includes an out-of-band data facility.
Advanced Topics for Stream Sockets Sending and Receiving Out-of-band Data vec.sv_onstack = 0; if (sigvector(SIGURG, &vec, (struct sigvec *) 0) < 0) { perror(“sigvector(SIGURG)”); } onurg() is a routine that handles out-of-band data in the client program. In addition, the socket's process group must be set, as shown below. The kernel will not send the signal to the process (or process group) unless this is done, even though the signal handler has been enabled.
Advanced Topics for Stream Sockets Sending and Receiving Out-of-band Data out-of-band pointer. However, once you read past the out-of-band pointer location with subsequent recv calls, the out-of-band byte can no longer be read. Usually the out-of-band data message indicates that all data currently in the stream can be flushed. This involves moving the stream pointer with successive recv calls, to the location of the out-of-band data pointer.
Advanced Topics for Stream Sockets Sending and Receiving Out-of-band Data printf(”received %c OOB\n”, mark); return; } 84 Chapter 3
4 Using Internet Datagram Sockets This chapter describes communication between processes using internet datagram sockets.
Using Internet Datagram Sockets Overview Overview Internet UDP datagram sockets provide bidirectional flow of data with record boundaries preserved. However, messages are not guaranteed to be reliably delivered. If a message is delivered, there is no guarantee that it is in sequence and unduplicated, but the data in the message are guaranteed to be intact. Datagram sockets allow you to send and receive messages without establishing a connection. Each message includes a destination address.
Using Internet Datagram Sockets Overview Table 4-1 Exchanging Data Between Internet Datagram Sockets Client Process Activity System Call Used Server Process Activity System Call Used create a socket socket() create a socket socket() bind a socket address bind() bind a socket address bind() send message sendto() or sendmsg() receive message recvfrom() or recvmsg() send message sendto() or sendmsg() receive message recvfrom() or recvmsg() Each of these steps or activities is described in m
Using Internet Datagram Sockets Preparing Address Variables Preparing Address Variables Before your client process can make a request of the server process, you must establish the correct variables and collect the information that you need about the server process and the service provided. The server process needs to: • Declare socket address variables. • Assign a wildcard address. • Get the port address of the service that you want to provide.
Using Internet Datagram Sockets Preparing Address Variables Field Description short sin_family Specifies the address family and should always be set to AF_INET. u_short sin_port Specifies the port address. Assign this field when you bind the port address for the socket or when you get a port address for a specific service. struct in_addr sin_addr Specifies the internet address. Assign this field when you get the internet address for the remote host.
Using Internet Datagram Sockets Preparing Address Variables #include struct hostent *hp; /* point to host info for name server host */ ... servaddr.sin_family = AF_INET; hp = gethostbyname (argv[1]); servaddr.sin_addr.s_addr = ((struct in_addr *)(hp->h_addr))->s_addr; The argv[1] parameter is the host name specified in the client program command line. Refer to the gethostent(3N) man page for more information on gethostbyname.
Using Internet Datagram Sockets Preparing Address Variables When to Get Server's Socket Address The server process should get the server’s socket address before binding. The client process should get the server’s socket address before client requests the service from the host. Refer to the getservent(3N) man page for more information on getservbyname. Using a Wildcard Local Address Wildcard addressing simplifies local address binding.
Using Internet Datagram Sockets Writing the Server and Client Processes Writing the Server and Client Processes This section explains the calls your server and client processes must make. Creating Sockets Both processes must call socket to create communication endpoints. socket and its parameters are described in the following table. Include files: #include #include
Using Internet Datagram Sockets Writing the Server and Client Processes When to Create Sockets The server or client process should create a socket before any other BSD Sockets system calls. Refer to the socket(2) man page for more information on socket. Binding Socket Addresses to Datagram Sockets After each process has created a socket, it must call bind to bind a socket address. Until an address is bound, other processes have no way to reference it.
Using Internet Datagram Sockets Writing the Server and Client Processes Parameter Description of Contents INPUT Value s socket descriptor of local socket socket descriptor of socket to be bound addr socket address pointer to address to be bound to s addrlen length of socket address size of struct sockaddr_in_address Function result: 0 if bind is successful, –1 if failure occurs. Example: struct sockaddr_in myaddr; ...
Using Internet Datagram Sockets Sending and Receiving Messages Sending and Receiving Messages The sendto and recvfrom (or sendmsg and recvmsg) system calls are usually used to transmit and receive messages. Sending Messages Use sendto or sendmsg to send messages. sendmsg allows the send data to be gathered from several buffers. If you have declared a default address, you can use send , sendto, or sendmsg to send messages.
Using Internet Datagram Sockets Sending and Receiving Messages Parameter Description of Contents INPUT Value flags settings for optional flags 0 (no options are currently supported) to address of recipient socket pointer to the socket address that message should be sent to tolen size of to length of address structure that to points to Function result: Number of bytes actually sent, –1 in the event of an error.
Using Internet Datagram Sockets Sending and Receiving Messages recv can also be used if you do not need to know what socket sent the message. However, if you want to send a response to the message, you must know where it came from. Except for the extra information returned by recvfrom and recvmsg, the three calls are identical. recv is described in the “Receiving Data” section of the “BSD Sockets: Using Internet Stream Sockets” chapter in this guide and in the recv(2) man page.
Using Internet Datagram Sockets Sending and Receiving Messages Parameter Contents INPUT Value OUTPUT Value flags settings for optional flags 0 or MSG_PEEK unchanged from address of socket that sent message pointer to address structure, not used for input pointer to socket address of socket that sent the message fromlen pointer to the size of from pointer to size of from pointer to the actual size of address returned Function result: Number of bytes actually received, –1 if an error occurs.
Using Internet Datagram Sockets Sending and Receiving Messages • MSG_PEEK for a nondestructive read. Use the MSG_PEEK option to preview an incoming message. If this option is set on a recvfrom, any message returned remains in the data buffer as though it had not been read yet. The next recvfrom will return the same message. When to Receive Data The client or server process should receive data after sockets are bound. Refer to the recv(2) man page for more information on recvfrom and recvmsg.
Using Internet Datagram Sockets Closing a Socket Closing a Socket In most applications, you do not have to worry about cleaning up your sockets. When you exit your program and your process terminates, the sockets are closed for you. If you need to close a socket while your program is still running, use the HP-UX file system call close. You may have more than one process with the same socket descriptor if the process with the socket descriptor executes a fork.
Using Internet Datagram Sockets Example Using Datagram Sockets Example Using Datagram Sockets NOTE These programs are provided as examples only of datagram socket usage and are not Hewlett-Packard supported products. These program examples demonstrate how to set up and use datagram sockets. These sample programs can be found in the /usr/lib/demos/networking/socket directory. The client program is intended to run in conjunction with the server program. This example implements a simple name server.
Using Internet Datagram Sockets Example Using Datagram Sockets #include #include #include #include
Using Internet Datagram Sockets Example Using Datagram Sockets */ myaddr_in.sin_addr.s_addr = INADDR_ANY; /* Find the information for the ”example” server * in order to get the needed port number. */ sp = getservbyname (”example”, ”udp”); if (sp == NULL) { printf(”%s: host not found”, argv[0]); exit(1); } myaddr_in.sin_port = sp->s_port; /* Create the socket.
Using Internet Datagram Sockets Example Using Datagram Sockets /* This will open the /etc/hosts file and keep * it open. This will make accesses to it faster. * If the host has been configured to use the NIS * server or name server (BIND), it is desirable * not to call sethostent(1), because a STREAM * socket is used instead of datagrams for each * call to gethostbyname().
Using Internet Datagram Sockets Example Using Datagram Sockets sendto (s, &reqaddr, sizeof(struct in_addr), 0, &clientaddr_in, addrlen); } default: /* Parent process comes here. */ exit(0); } } /* * C L I E N T . U D P * * This is an example program that demonstrates the use of * datagram sockets as an BSD Sockets mechanism. This contains * the client, and is intended to operate in conjunction with the * server program found in serv.udp.
Using Internet Datagram Sockets Example Using Datagram Sockets struct in_addr reqaddr; /* for returned internet address */ #define ADDRNOTFOUND 0xffffffff /* value returned for unknown host */ #define RETRIES 5 /* # of times to retry before giving up */ /* * H A N D L E R * * This routine is the signal handler for the alarm signal. * It simply re-installs itself as the handler and returns.
Using Internet Datagram Sockets Example Using Datagram Sockets exit(1); } servaddr_in.sin_addr.s_addr = ((struct in_addr *) (hp->h_addr))->s_addr; /* Find the information for the ”example” server * in order to get the needed port number. */ sp = getservbyname (”example”, ”udp”); if (sp == NULL) { fprintf(stderr, ”%s: example not found in /etc/services\n”, argv[0]); exit(1); } servaddr_in.sin_port = sp->s_port; again: /* Create the socket.
Using Internet Datagram Sockets Example Using Datagram Sockets if (recv (s, &reqaddr, sizeof(struct in_addr), 0) == -1) { if (errno == EINTR) { /* Alarm went off & aborted the receive. * Need to retry the request if we have * not already exceeded the retry limit. */ if (—retry) { goto again; } else { printf(”Unable to get response from”); printf(” %s after %d attempts.
5 Advanced Topics for Internet Datagram Sockets This chapter explains the following: 109
Advanced Topics for Internet Datagram Sockets • SO_BROADCAST socket option. • Specifying a default socket address. • Synchronous I/O multiplexing with select. • Sending and receiving data asynchronously. • Sending and receiving IP multicast datagrams. • Nonblocking I/O. • Using broadcast addresses.
Advanced Topics for Internet Datagram Sockets SO_BROADCAST Socket Option SO_BROADCAST Socket Option This option is AF_INET socket-specific. SO_BROADCASTADDR establishes permission to send broadcast datagrams from the socket.
Advanced Topics for Internet Datagram Sockets Specifying a Default Socket Address Specifying a Default Socket Address It is possible (but not required) to specify a default address for a remote datagram socket. This allows you to send messages without specifying the remote address each time. In fact, if you use sendto or sendmsg, an error occurs if you enter any value other than 0 for the socket address after the default address has been recorded.
Advanced Topics for Internet Datagram Sockets Specifying a Default Socket Address Include files: #include #include #include
Advanced Topics for Internet Datagram Sockets Synchronous I/O Multiplexing with Select Synchronous I/O Multiplexing with Select The select system call can be used with sockets to provide a synchronous multiplexing mechanism. The system call has several parameters which govern its behavior. If you specify a zero pointer for the timeout parameter timout, select will block until one or more of the specified socket descriptors is ready.
Advanced Topics for Internet Datagram Sockets Sending and Receiving Data Asynchronously Sending and Receiving Data Asynchronously Asynchronous sockets allow a user program to receive an SIGIO signal when the state of the socket changes. This state change can occur, for example, when new data arrive. More information on SIGIO can be found in the “Advanced Topics for Internet Stream Sockets” chapter of this guide.
Advanced Topics for Internet Datagram Sockets Sending and Receiving IP Multicast Datagrams Sending and Receiving IP Multicast Datagrams IP multicasting provides a mechanism for sending a single datagram to a group of systems. Normally, only systems that have joined the multicast group process the datagrams. Multicast datagrams are transmitted and delivered with the same “best effort” reliability as regular unicast IP datagrams.
Advanced Topics for Internet Datagram Sockets Sending and Receiving IP Multicast Datagrams Normally, multicast datagrams are sent only to systems directly connected to the same network that the sending interface is on. If multicast datagrams are intended for distant networks, a special multicast router must be present on the local and intermediate networks. A socket option IP_MULTICAST_TTL controls the number of intermediate systems through which a multicast datagram can be forwarded.
Advanced Topics for Internet Datagram Sockets Sending and Receiving IP Multicast Datagrams #include unsigned char ttl = 64; setsockopt(s, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl)); Note that ttl is an unsigned char. Any of the values 0 through 255 can be specified. If ttl is zero, the multicast is limited to the local system. If ttl is one, the multicast is limited to a local network. If ttl is two, the multicast can forwarded through at most one gateway; and so forth.
Advanced Topics for Internet Datagram Sockets Sending and Receiving IP Multicast Datagrams because the system uses some link-layer multicast addresses. For example, the E/ISA interface card is limited to 16 multicast addresses, and the system uses two of those. So all applications in the system can join at most 14 unique multicast groups on each E/ISA interface. An application automatically leaves a multicast group when it terminates, either normally or abnormally.
Advanced Topics for Internet Datagram Sockets Sending and Receiving IP Multicast Datagrams Note that imr_interface must match the field that was used when the IP_ADD_MEMBERSHIP socket option was specified for imr_multiaddr. Sharing a Multicast Port SO_REUSEPORT If more than one application may bind to the same port number on a system, each application must set the SO_REUSEPORT socket option before binding to the port. For example: #include
Advanced Topics for Internet Datagram Sockets Nonblocking I/O Nonblocking I/O Sockets are created in blocking mode I/O by default. You can specify that a socket be put in nonblocking mode by using the ioctl system call with the FIOSNBIO request. An example usage of this call is: #include ... ioctl(s,FIOSNBIO,&arg); arg is a pointer to int: • When int equals 0, the socket is changed to blocking mode. • When int equals 1, the socket is changed to nonblocking mode.
Advanced Topics for Internet Datagram Sockets Using Broadcast Addresses Using Broadcast Addresses In place of a unique internet address or the wildcard address, you can also specify a broadcast address. A broadcast address is an internet address with a local address portion of all 1s. If you use broadcast addressing, be careful not to overload your network.
6 Using UNIX Domain Stream Sockets This chapter describes creating a UNIX Domain stream socket connection between two processes executing on the same node.
Using UNIX Domain Stream Sockets Overview Overview UNIX Domain (AF_UNIX) stream sockets provide bidirectional, reliable, unduplicated flow of data without record boundaries. They offer significant performance increases when compared with the use of local internet (AF_INET) sockets, due primarily to lower code execution overhead. The following table lists the steps involved in creating and terminating a UNIX Domain BSD Sockets connection using stream sockets.
Using UNIX Domain Stream Sockets Overview Client Process Activity System Call Used receive data read() or recv() disconnect socket (optional) shutdown() or close() Server Process Activity System Call Used send data write() or send() disconnect socket (optional) shutdown() or close() Each of these steps or activities is described in more detail in the following sections. The description of each activity specifies a system call and includes: • What happens when the system call is used.
Using UNIX Domain Stream Sockets Preparing Address Variables Preparing Address Variables Before you begin to create a connection, establish the correct variables and collect the information that you need to request a connection. Your server process needs to: • Declare socket address variables. • Get the pathname (character string) for the service you want to provide. Your client process needs to: • Declare socket address variables. • Get the pathname (character string) for the service you want to use.
Using UNIX Domain Stream Sockets Preparing Address Variables The server process only needs an address for its own socket. Your client process will not need an address for its own socket.
Using UNIX Domain Stream Sockets Writing the Server Process Writing the Server Process This section explains the calls your server process must make to connect with and serve a client process. Creating a Socket The server process must call socket to create a communication endpoint. socket and its parameters are described in the following table. Include files: #include #include
Using UNIX Domain Stream Sockets Writing the Server Process Binding a Socket Address to the Server Process's Socket After your server process has created a socket, it must call bind to bind a socket address. Until an address is bound to the server socket, other processes have no way to reference it. The server process must bind a specific pathname to this socket, which is used for listening. Otherwise, a client process would not know what pathname to connect to for the desired service.
Using UNIX Domain Stream Sockets Writing the Server Process Setting the Server Up to Wait for Connection Requests Once your server process has an address bound to it, it must call listen to set up a queue that accepts incoming connection requests. The server process then monitors the queue for requests (using select(2) or accept ). The server process cannot respond to a connection request until it has executed listen. listen and its parameters are described in the following table.
Using UNIX Domain Stream Sockets Writing the Server Process Accepting a Connection The server process can accept any connection requests that enter its queue after it executes listen. accept creates a new socket for the connection and returns the socket descriptor for the new socket. The new socket: • Is created with the same properties as the old socket. • Has the same bound pathname as the old socket. • Is connected to the client process' socket.
Using UNIX Domain Stream Sockets Writing the Server Process Function result: socket descriptor of new socket if accept is successful, –1 if failure occurs. Example: struct sockaddr_un peeraddr; ... addrlen = sizeof(sockaddr_un); s = accept (ls, &peeraddr, &addrlen); There is no way for the server process to indicate which requests it can accept. It must accept all requests or none. When to Accept a Connection The server process should accept a connection after executing the listen call.
Using UNIX Domain Stream Sockets Writing the Client Process Writing the Client Process This section discusses the calls your client process must make to connect with and be served by a server process. Creating a Socket The client process must call socket to create a communication endpoint. socket and its parameters are described in the following table. Include files: #include #include
Using UNIX Domain Stream Sockets Writing the Client Process Requesting a Connection Once the server process is listening for connection requests, the client process can request a connection with the connect call. connect and its parameters are described in the following table. Include files: #include #include #include
Using UNIX Domain Stream Sockets Writing the Client Process When to Request a Connection The client process should request a connection after socket is created and after server socket has a listening socket. Refer to the connect(2) man page for more information on connect.
Using UNIX Domain Stream Sockets Sending and Receiving Data Sending and Receiving Data After the connect and accept calls are successfully executed, the connection is established and data can be sent and received between the two socket endpoints. Because the stream socket descriptors correspond to HP-UX file descriptors, you can use the read and write calls (in addition to send and recv) to pass data through a socket-terminated channel.
Using UNIX Domain Stream Sockets Sending and Receiving Data Function result: number of bytes actually sent, –1 if failure occurs. Example: count = send (s, buf, 10, 0); send blocks until the specified number of bytes have been queued to be sent, unless you are using nonblocking I/O. When to Send Data The server or client process should send data after connection is established. Refer to the send(2) man page for more information on send.
Using UNIX Domain Stream Sockets Sending and Receiving Data No more than len bytes of data are received. If there are more than len bytes of data on the socket, the remaining bytes are received on the next recv. Flag Options There are no flag options for UNIX Domain (AF_UNIX) sockets. The only supported value for this field is 0. When to Receive Data The server or client process should receive data after connection is established. Refer to the recv(2) man page for more information on recv.
Using UNIX Domain Stream Sockets Closing a Socket Closing a Socket In most applications, you do not have to worry about cleaning up your sockets. When you exit your program and your process terminates, the sockets are closed for you. If you need to close a socket while your program is still running, use the close system call. For example, you may have a daemon process that uses fork to create the server process.
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets NOTE These programs are provided as examples only of UNIX Domain stream socket usage and are not Hewlett-Packard supported products. These programming examples demonstrate how to set up and use UNIX Domain stream sockets. These sample programs can be found in the /usr/lib/demos/networking/af_unix directory. The client program is intended to run in conjunction with the server program.
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets cc = send(fd, buf, buflen, 0); if (cc == -1) { perror(”send”); exit(0); } buf += cc; buflen -= cc; } } recv_data(fd, buf, buflen) char *buf; { int cc; while (buflen > 0) { cc = recv(fd, buf, buflen, 0); if (cc == -1) { perror(”recv”); exit(0); } buf += cc; buflen -= cc; } } main(argc, argv) int argc; char *argv[]; { int bufsize, bytes, cc, i, total, pid, counter_pid; float msec; struct timeval tp1, tp2; int ns, recvsize, secs, usec; s
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets perror(”catch - socket failed”); exit(0); } bufsize = BUFSIZE; /* * Use setsockopt() to change the socket buffer size to improve * throughput for large data transfers */ if ((setsockopt(s, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(bufsize))) == -1) { perror(”catch - setsockopt failed”); exit(0); } /* * Bind the server socket to its name */ if ((bind(s, &sa, sizeof(struct sockaddr_un))) == -1) { perror(”catch - bind failed”); exit(0); }
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets */ send_data(ns, &bullet, sizeof(struct bullet)); cc = 0; if (counter_pid) kill(counter_pid, SIGUSR1); if (gettimeofday(&tp1, &tzp) == -1) { perror(”catch time of day failed”); exit(0); } /* * Receive data from the client */ total = 0; i = bytes; while (i > 0) { cc = recvsize < i ? recvsize : i; recv_data(ns, buffer, cc); total += cc; i -= cc; } /* * Calculate throughput */ if (gettimeofday(&tp2, &tzp) == -1) { perror(”catch time of d
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets * PITCH - SEND DATA TO THE CATCHER * * Pitch and catch set up a simple unix domain stream socket * client-server connection. The client (pitch) then sends * data to the server (catch), throughput is calculated, and * the result is printed to the client's stdout. */ #include #include #include #include #include #include #include
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets /* * The SIGPIPE signal will be received if the peer has gone away * and an attempt is made to write data to the peer. Ignoring * the signal causes the write operation to receive an EPIPE error. * Thus, the user is informed about what happened.
Using UNIX Domain Stream Sockets Example Using UNIX Domain Stream Sockets if (gettimeofday(&tp1, &tzp) == -1) { perror(”pitch time of day failed”); exit(0); } i = bytes; total = 0; /* * Send the data */ while (i > 0) { cc = sendsize < i ? sendsize : i; send_data(s, buffer, cc); i -= cc; total += cc; } /* * Receive the bullet to calculate throughput */ recv_data(s, &bullet, sizeof(struct bullet)); if (gettimeofday(&tp2, &tzp) == -1) { perror(”pitch time of day failed”); exit(0); } if (pid) kill(pid, SIGUSR2)
7 Using UNIX Domain Datagram Sockets This chapter describes communication between processes using UNIX Domain datagram sockets.
Using UNIX Domain Datagram Sockets Overview Overview The UNIX Domain only allows communication between processes executing on the same machine. In contrast to pipes, it does not require the communicating processes to have common ancestry. For more information on the UNIX Domain protocol, refer to the unix(7p) man page. UNIX domain (AF_UNIX) datagram sockets provide bidirectional, reliable, unduplicated flow of data while preserving record boundaries.
Using UNIX Domain Datagram Sockets Overview Table 7-1 Exchanging Data Between UNIX Domain Datagram Sockets Client Process Activity System Call Used Server Process Activity System Call Used create a socket socket() create a socket socket() bind a socket bind() bind a socket bind() send message sendto() or sendmsg() receive message recvfrom() or recvmsg() send message sendto() or sendmsg() receive message recvfrom() or recvmsg() Each of these steps or activities is described in more detail
Using UNIX Domain Datagram Sockets Preparing Address Variables Preparing Address Variables Before your client process can make a request of the server process, you must establish the correct variables and collect the information you need about the server process. Your server process needs to: • Declare socket address variables. • Get the pathname (character string) for the service you want to provide. Your client process needs to: • Declare socket address variables.
Using UNIX Domain Datagram Sockets Preparing Address Variables The server process only needs one address for its socket. Any process that knows the address of the server process can then send messages to it. Thus, your client process needs to know the address of the server socket. The client process will not need an address for its own socket, unless other processes need to refer to the client process.
Using UNIX Domain Datagram Sockets Writing the Server and Client Processes Writing the Server and Client Processes This section discusses the calls your server and client processes must make. Creating Sockets Both processes must call socket to create communication endpoints. socket and its parameters are described in the following table. Include files: #include #include
Using UNIX Domain Datagram Sockets Writing the Server and Client Processes Binding Socket Addresses to UNIX Domain Datagram Sockets After your server process has created a socket, it must call bind to bind a socket address. Until the server socket is bound to an address, other processes have no way to reference it. The server process must bind a specific pathname to its socket. Set up the address structure with a local address before the server makes a call to bind.
Using UNIX Domain Datagram Sockets Writing the Server and Client Processes strcpy(servaddr.sun_path, SOCKET_PATH); unlink(SOCKET_PATH); bind(s, &servaddr, sizeof(struct sockaddr_un)); When to Bind Socket Addresses The server process should bind socket addresses after socket is created and before any other BSD Sockets system calls. Refer to the bind(2) man page for more information on bind.
Using UNIX Domain Datagram Sockets Sending and Receiving Messages Sending and Receiving Messages The sendto and recvfrom (or sendmsg and recvmsg) system calls are usually used to transmit and receive messages with datagram sockets. Sending Messages Use sendto or sendmsg to send messages. sendmsg is similar to sendto, except sendmsg allows the send data to be gathered from several buffers. sendto and its parameters are described in the following table. Include files: #include
Using UNIX Domain Datagram Sockets Sending and Receiving Messages Function result: number of bytes actually sent if sendto succeeds, -1 if sendto call fails. Example: struct sockaddr_un servaddr; ... count = sendto(s, argv[2], strlen(argv[2]), 0, &servaddr, sizeof(struct sockaddr_un); When to Send Data The server or client process should send data after server has bound to an address. Refer to the send(2) man page for more information on sendto and sendmsg.
Using UNIX Domain Datagram Sockets Sending and Receiving Messages Parameter Contents OUTPUT Value INPUT Value s socket descriptor of local socket socket descriptor of socket receiving the message unchanged msg pointer to data buffer pointer to buffer that is to receive data pointer to received data len maximum number of bytes that should be received size of data buffer unchanged flags settings for optional flags 0 (no options are supported unchanged from address of socket that sent mes
Using UNIX Domain Datagram Sockets Sending and Receiving Messages message is in the queue, it is not affected. Therefore, the best technique is to receive as much as possible on each call. Refer to the recv(2) man page for more information on recvfrom and recvmsg.
Using UNIX Domain Datagram Sockets Closing a Socket Closing a Socket In most applications, you do not have to close the sockets. When you exit your program and your process terminates, the sockets are closed for you. If you need to close a socket while your program is still running, use the close system call. You may have more than one process with the same socket descriptor if the process with the socket descriptor executes a fork.
Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets NOTE These programs are provided as examples only of UNIX Domain datagram socket usage and are not Hewlett-Packard supported products. These programming examples demonstrate how to set up and use UNIX Domain datagram sockets. These sample programs can be found in the /usr/lib/demos/networking/af_unix directory.
Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets alarm((unsigned long) 120); /* Create a UNIX datagram socket for server if ((sock = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) { perror(”server: socket”); exit(1); } /* Set up address structure for server socket */ */ bzero(&servaddr, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; strcpy(servaddr.
Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets * */ #include #include #include #include #include #include #include
Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets perror(”client: bind”); exit(3); } /* Set up address structure for server socket */ bzero(&servaddr, sizeof(servaddr)); servaddr.sun_family = AF_UNIX; strcpy(servaddr.
Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets 164 Chapter 7
8 Programming Hints This chapter contains information for: • Troubleshooting. • Using diagnostic utilities as troubleshooting tools.
Programming Hints • Adding a server process to the internet daemon. • Summary tables for system and library calls. • Portability issues.
Programming Hints Troubleshooting Troubleshooting The first step to take is to avoid many problems by using good programming and debugging techniques. Your programs should check for a returned error after each system call and print any that occur. For example, the following program lines print an error message for read: cc=read(sock,buffer,1000); if (cc<0) { perror (“reading message”) exit(1) } Refer to the perror(3C) man page for more information .
Programming Hints Using Diagnostic Utilities as Troubleshooting Tools Using Diagnostic Utilities as Troubleshooting Tools You can use the following diagnostic utilities to help debug your programs. It is helpful if you have multiple access to the system so you can obtain information about the program while it is running. ping Use ping to verify the physical connection with the destination node.
Programming Hints Adding a Server Process to the Internet Daemon Adding a Server Process to the Internet Daemon This section contains example BSD Sockets programs that use the internet daemon, called inetd. For more information on inetd, refer to the inetd(1M) man page. You can invoke the example server programs from inetd if you have super-user capabilities and you make the following configuration modifications: • Add the following lines to the /etc/inetd.
Programming Hints Adding a Server Process to the Internet Daemon * M A I N * * This is the actual server routine that the /etc/inetd forks to * handle each individual connection. Its purpose is to receive * the request packets from the remote client, process them, * and return the results to the client. * */ main() { char buf[10]; /* This example uses 10 byte messages. */ int len, lenl; /* Go into a loop, receiving requests from the remote * client.
Programming Hints Adding a Server Process to the Internet Daemon exit (0); } /* * S E R V E R . U D P * * This is a variation of the example program called serv.udp. * This one performs the same function, except that it is * designed to be called from /etc/inetd. This version does * not contain a daemon loop, and does not wait for requests * to arrive on a socket. /etc/inetd does these functions.
Programming Hints Adding a Server Process to the Internet Daemon * BUFFERSIZE - 1 bytes are read so that * room is left at the end of the buffer * for a null character. */ cc = recvfrom(0, buffer, BUFFERSIZE - 1, 0 &clientaddr_in, &addrlen); if ( cc == -1) exit(1); /* Make sure the message received in * null terminated. */ buffer[cc]='\0'; /* Treat the message as a string containing * a hostname. Search for the name * in /etc/hosts. */ hp = gethostbyname (buffer); if (hp == NULL) { /* Name was not found.
Programming Hints Summary Tables for System and Library Calls Summary Tables for System and Library Calls The following table contains a summary of the BSD Sockets system calls. Table 8-1 BSD Sockets System Calls System Call Description socket Creates a socket, or communication endpoint for the calling process. bind Assigns a socket address to the socket specified by the calling process. listen Sets up a queue for incoming connection requests. (Stream sockets only.
Programming Hints Summary Tables for System and Library Calls System Call Description getsockname Gets the socket address of the specified socket. getsockopt, setsockopt Gets, or sets, the options associated with a socket. getpeername Gets the name of the peer socket connected to the specified socket. The following table contains a summary of the other system calls that can be used with BSD Sockets.
Programming Hints Summary Tables for System and Library Calls System Call Description select Can be used to improve efficiency for a process that accesses multiple sockets or other I/O devices simultaneously. Refer to the sections on “Synchronous I/O Multiplexing with Select.” ioctl Can be used for finding the number of receivable bytes with FIONREAD and for setting the nonblocking I/O flag with FIOSBNBIO. Can also be used for setting a socket to receive asynchronous signals with FIOASYNC .
Programming Hints Summary Tables for System and Library Calls Table 8-3 Library Calls Library Call Description inet_addr inet_lnaof inet_makeaddr inet_netof inet_network internet address manipulation routines setservent endservent getservbyname getservbyport getservent get or set service entry setprotoent endprotoent getprotobyname getprotobynumber getprotoent get or set protocol entry setnetent endnetent getnetbyaddr getnetbyname getnetent get or set network entry sethostent endhostent gethostby
Programming Hints Portability Issues Portability Issues This section describes implementation differences between 4.3 BSD Sockets and HP-UX IPC. It contains porting issues for: • IPC functions and library calls. • Other functions and library calls typically used by IPC programs. Because HP-UX IPC is based on 4.3 BSD Sockets (it is a subset of 4.3 BSD), programs should port easily between HP-UX and 4.3 BSD systems.
Programming Hints Portability Issues FIONREAD Return Values For HP-UX systems, the FIONREAD ioctl request on a datagram socket returns a number that may be larger than the number of bytes actually readable. Previously, HP-UX systems returned the maximum number of bytes that a subsequent recv would be able to return. Listen's Backlog Parameter HP-UX sets the actual size of the queue for pending connections to 3/ 2*B+1, where B is the backlog value specified in the listen() function.
Programming Hints Portability Issues Utmp The 4.3 BSD /etc/utmp file format is incompatible with the HP-UX implementation. The HP-UX implementation uses UNIX System V compatible calls. Refer to the utmp(4) man page for details. Library Equivalencies Certain commonly used library calls in 4.3 BSD are not present in HPUX systems, but they do have HP-UX equivalents. To make code porting easier, use the following equivalent library calls.
Programming Hints Portability Issues 180 Chapter 8
A BSD Sockets Quick Reference Table This appendix compares HP-UX BSD Sockets and X/Open Sockets.
BSD Sockets Quick Reference Table Quick Reference Table Quick Reference Table Release 10.10 of the HP-UX operating system supports two variations of sockets--HP-UX BSD Sockets and X/Open Sockets. To use X/Open sockets, users must make an addition to their make files by including the “-l xnet” argument with the “c89” or “cc” utilities. For detailed information about HP- UX BSD sockets, see this manual as well as the man pages.
BSD Sockets Quick Reference Table Quick Reference Table HP-UX getpeername X/Open getpeername int getpeername (int socket, void *address, int *address_len); getsockname int getpeername (int socket, struct sockaddr *address, size_t *address_len); getsockname int getsockname (int socket, void *address, int *address_len); getsockopt int getsockname (int socket, struct sockaddr *addr, size_t *address_len); getsockopt int getsockopt (int socket, int level, int option_name, void *option_value, int *option_l
BSD Sockets Quick Reference Table Quick Reference Table HP-UX recvmsg X/Open recvmsg int recvmsg (int socket, struct msghdr msg[], int flags); select ssize_t recvmsg (int socket, struct msghdr *msg, int flags); select int select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); send int select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout); send int send (int socket, const void *buffer, int length, int flags); sendmsg
BSD Sockets Quick Reference Table Quick Reference Table HP-UX socketpair X/Open socketpair int socketpair (int af, int type, int protocol, int sv[2]); write(2) int socketpair (int domain, int type, int protocol, int socketvector[2]); write(2) ssize_t write (int fildes, const void *buf, size_t nbyte); writev ssize_t write (int fildes, const void *buf, size_t nbyte); writev ssize_t writev (int fildes, const struct iovec *iov, int iovcnt); Appendix A ssize_t writev (int fildes, const struct iovec *iov
BSD Sockets Quick Reference Table Quick Reference Table 186 Appendix A
Glossary Address family: The address format used to interpret addresses specified in socket operations. The internet address family (AF_INET) is supported. Address: An Interprocess Communication term that refers to the means of labeling a socket so that it is distinguishable from other sockets, and routes to that socket are able to be determined. Advanced Research Projects Agency: A U.S. government research agency that was instrumental in developing and using the original ARPA Services on the ARPANET.
Glossary UNIX software released by the University of California at Berkeley. pair of sockets at either end of the connection. See also, “Association.” Binding: Establishing the address of a socket which allows other sockets to connect to it or to send data to it. Daemon: A software process that runs continuously and provides services on request. BSD: See Berkeley Software Distribution. DARPA: See Defense Advanced Channel: A communication path created by establishing a connection between sockets.
Glossary services. Domain: A set of allowable names or values. See also, “Communication domain.” File Transfer Protocol: The file transfer protocol that is traditionally used in ARPA networks. The ftp command uses the FTP protocol. Forwarding: The process of forwarding a mail message to another destination (i.e., another user name, host name or network). Organization: Called “ISO,” this organization created a network model that identifies the seven commonly-used protocol levels for networking.
Glossary IPC: See Interprocess Communication. ISO: See International Standards Organization. Link-level address: A sixbyte quantity that is distinct from the internet address and is the unique address of the LAN interface card on each LAN. Message: In IPC, the data sent in one UDP packet. When using sendmail a message is the information unit transferred by mail. Node: A computer system that is attached to or is part of a computer network.
Glossary Socket: Addressable entities that are at either end of an Interprocess Communication connection. A socket is identified by a socket descriptor. A program can write data to and read data from a socket, just as it writes and reads data to and from files. Socket address: The internet address, port address and address family of a socket. The port and internet address combination allows the network to locate a socket.
Glossary processes executing on the same node and using the AF_UNIX socket address family. User Datagram Protocol: A protocol that provides the underlying communication support for datagram sockets. UDP is an unreliable protocol. A process receiving messages on a datagram socket could find that messages are duplicated, out-of-sequence or missing. Messages retain their record boundaries and are sent as individually addressed packets. There is no concept of a connection between the communicating sockets.
Index A accept domain stream sockets, 124, 130, 136 Internet stream sockets, 29, 37, 43 nonblocking I/O, 77 pending connections, 178 summary table, 173 address conversion call, 48 addressing domain, 31, 126, 150 AF_INET, 18, 19, 28, 89 AF_UNIX, 18, 19, 124 Asynchronous examples, 76 sockets, 115 B bcmp, 179 bcopy, 179 bind datagram sockets, 87, 93 domain datagram sockets, 149 domain stream sockets, 124 example usage, 66 Internet stream sockets, 29, 87 summary table, 173 blocking mode, 121 broadcast address,
Index BSD IPC connections, 29, 124 BSD IPC system calls, 173 BSD IPC using datagram sockets, 86 channel, 18 client, 21 client-server model, 21 closing a socket, 47, 100, 139, 159 communication domain, 18 Creating a Socket, 128 creating a socket, 35, 40, 133 creating sockets, 92 datagram sockets, 18, 86 declaring socket address variables, 31, 88, 126 example using stream sockets, 48 examples using datagram sockets, 101 FIONREAD, 178 FIOSBNIO, 77 Flag Options, 45 flag options, 98, 138 getting and setting soc
Index preparing address variables, 150 sockaddr_un, 150 ioctl, 77, 121, 175 IP multicasting, 116 IP_ADD_MEMBERSHIP, 119 IP_DROP_MEMBERSHIP, 119 IP_MAX_MEMBERSHIPS, 118 IP_MULTICAST_IF, 117 IP_MULTICAST_LOOP, 118 IP_MULTICAST_TTL, 117 IPC connections, 17, 29, 35, 124, 128 L library calls, 177, 179 listen backlog parameter, 178 domain stream sockets, 124, 130 Internet stream sockets, 29, 37, 124 summary table, 173 M memcmp, 179 memcpy, 179 memset, 179 MSG_OOB, 45 MSG_PEEK, 45 N netstat, 168 Network event log
Index SO_KEEPALIVE, 61, 66 SO_LINGER, 61, 68 SO_OOBINLINE, 61 SO_RCVBUF, 61, 67 SO_RCVLOWAT, 61 SO_RCVTIMEO, 61, 62 SO_REUSEADDR, 61, 66 SO_REUSEPORT, 61, 62 SO_SNDBUF, 61, 67 SO_SNDLOWAT, 61 SO_SNDTIMEO, 61, 62 SO_TYPE, 61 SO_USELOOPBACK, 61 socket, 29, 87, 124, 149 domain datagram sockets, 149 socket address, 88 sockets, 18 sprintf, 179 strchr, 179 stream sockets, 173 strrchr, 179 synchronous signals, 75 sockets, 75 T TCP, 19 U UDP, 19 UNIX Domain address family, 18, 19 datagram sockets, 147 stream socke