hit counter script
HP Rp3440-4 - 9000 - 0 MB RAM Programmer's Manual
HP Rp3440-4 - 9000 - 0 MB RAM Programmer's Manual

HP Rp3440-4 - 9000 - 0 MB RAM Programmer's Manual

Bsd sockets interface programmer’s guide
Hide thumbs Also See for Rp3440-4 - 9000 - 0 MB RAM:
Table of Contents

Advertisement

BSD Sockets Interface Programmer's
Guide
Edition 6
B2355-90136
HP 9000 Networking
E0497
Printed in: United States
© Copyright 1997 Hewlett-Packard Company.

Advertisement

Table of Contents
loading

Summary of Contents for HP Rp3440-4 - 9000 - 0 MB RAM

  • Page 1 BSD Sockets Interface Programmer’s Guide Edition 6 B2355-90136 HP 9000 Networking E0497 Printed in: United States © Copyright 1997 Hewlett-Packard Company.
  • Page 2: Legal Notices

    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...
  • Page 3 ©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. ©copyright 1990, 1991, 1992 Cornell University ©copyright 1989-1991 The University of Maryland ©copyright 1988 Carnegie Mellon University Trademark Notices UNIX is a registered trademark in the United...
  • Page 5: Table Of Contents

    Contents 1. BSD Sockets Concepts Introduction ..........17 Key Terms and Concepts .
  • Page 6 Contents Example Using Internet Stream Sockets ......48 3. Advanced Topics for Stream Sockets Socket Options ..........61 Getting and Setting Socket Options.
  • Page 7 Contents 4. Using Internet Datagram Sockets Overview ..........86 Preparing Address Variables .
  • Page 8 Contents Using Broadcast Addresses ........122 6. Using UNIX Domain Stream Sockets Overview .
  • Page 9 Contents Sending and Receiving Messages ......155 Sending Messages ........155 Receiving Messages .
  • Page 10 Contents...
  • Page 11: Printing History

    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.
  • Page 13 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).
  • Page 14 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.
  • Page 15: Bsd Sockets Concepts

    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...
  • Page 16 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. BSD Sockets is a program development tool. Before you attempt to use NOTE BSD Sockets, you may need to familiarize yourself with the C programming language and the HP-UX operating system.
  • Page 17: Introduction

    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.
  • Page 18 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 channel...
  • Page 19 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.
  • Page 20: How You Can Use Bsd Sockets

    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.
  • Page 21: The Client-Server Model

    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.
  • Page 22 BSD Sockets Concepts The Client-Server Model Figure 1-1 Client-Server in a Pre-Connection State Chapter 1...
  • Page 23 BSD Sockets Concepts The Client-Server Model Figure 1-2 Client-Server at Time of Connection Request Chapter 1...
  • Page 24 BSD Sockets Concepts The Client-Server Model Figure 1-3 Client-Server When Connection is Established Chapter 1...
  • Page 25: Bsd Sockets Library Routines

    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”...
  • Page 26 BSD Sockets Concepts BSD Sockets Library Routines Chapter 1...
  • Page 27: Using Internet Stream Sockets

    Using Internet Stream Sockets...
  • Page 28 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”...
  • Page 29: Overview

    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. Table 2-1 Creating/Terminating BSD Sockets Connections Using Internet Stream Sockets...
  • Page 30 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. •...
  • Page 31: Preparing Address Variables

    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. •...
  • Page 32: Getting The Remote Host's Internet Address

    Using Internet Stream Sockets Preparing Address Variables Field Description Specifies the address family and should short sin_family always be set to AF_INET. Specifies the port address. Assign this field u_short sin_port when you bind the port address for the socket or when you get a port address for a specific service.
  • Page 33: Getting The Port Address For The Desired Service

    Using Internet Stream Sockets Preparing Address Variables #include <netdb.h> 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.
  • Page 34: Using A Wildcard Local Address

    Using Internet Stream Sockets Preparing Address Variables #include <netdb.h> 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.
  • Page 35: Writing The Server Process

    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.
  • Page 36: Binding A Socket Address To The Server Process's Socket

    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.
  • Page 37: Setting Up The Server To Wait For Connection Requests

    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.
  • Page 38: Accepting A Connection

    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.
  • Page 39 Using Internet Stream Sockets Writing the Server Process OUTPUT Parameter Contents INPUT Value Value socket socket descriptor of unchanged descriptor of server socket local socket addr socket address pointer to address pointer to structure where socket address will be put address of client socket that server’s...
  • Page 40: Writing The Client Process

    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.
  • Page 41: Requesting A Connection

    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 <sys/types.h>...
  • Page 42 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.
  • Page 43: Sending And Receiving Data

    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.
  • Page 44: Receiving Data

    Using Internet Stream Sockets Sending and Receiving Data Description of Parameter INPUT Value Contents pointer to data buffer pointer to data to be sent 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);...
  • Page 45: Flag Options

    Using Internet Stream Sockets Sending and Receiving Data Description of Parameter INPUT Value Contents socket descriptor of local socket descriptor of socket socket receiving data pointer to data buffer pointer to buffer that is to receive data maximum number of size of data buffer bytes that should be received...
  • Page 46 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.
  • Page 47: Closing A Socket

    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.
  • Page 48: 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.
  • Page 49 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.
  • Page 50 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.
  • Page 51 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.
  • Page 52 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.
  • Page 53 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.
  • Page 54 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.
  • Page 55 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 <remote host>\n” argv[0]; exit(1); /* clear out address structures */ memset ((char *)&myaddr_in, 0, sizeof(struct sockaddr_in));...
  • Page 56 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]);...
  • Page 57 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.
  • Page 58 Using Internet Stream Sockets Example Using Internet Stream Sockets Chapter 2...
  • Page 59: Advanced Topics For Stream Sockets

    Advanced Topics for Stream Sockets...
  • Page 60 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. •...
  • Page 61: Socket Options

    Advanced Topics for Stream Sockets Socket Options Socket Options The operation of sockets is controlled by socket level options. The following options are supported for internet stream sockets: • SO_REUSEADDR • SO_KEEPALIVE • SO_DONTROUTE • SO_SNDBUF • SO_RCVBUF • SO_LINGER •...
  • Page 62: Getting And Setting Socket 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.
  • Page 63 Advanced Topics for Stream Sockets Socket Options OUTPUT Parameter Contents INPUT Value Value socket socket descriptor unchanged descriptor for which option values are to be returned level protocol SOL_SOCKET unchanged level optname name of supported option unchanged option name optval pointer to pointer to buffer pointer to buffer...
  • Page 64 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 •...
  • Page 65: So_Reuseaddr

    Advanced Topics for Stream Sockets Socket Options Description of Parameter INPUT Value Contents optname name of option supported option name optval pointer to option input Must be at least size of value (int). Holds either value to be set or boolean flag optlen length of optval size of optval...
  • Page 66: So_Keepalive

    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).
  • Page 67: So_Dontroute

    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.
  • Page 68: So_Linger

    Advanced Topics for Stream Sockets Socket Options Table 3-1 Summary Information for Changing Socket Buffer Size SocketType (Protocol) stream (TCP) When Buffer Size at any time Increase Allowed When Buffer Size only prior to establishing a Decrease Allowed connection Maximum Buffer Size 262144 bytes SO_LINGER SO_LINGER controls the actions taken when a close is executed on a...
  • Page 69: So_Useloopback

    Advanced Topics for Stream Sockets Socket Options Table 3-2 Summary of Linger Options on Close Wait Does Not Socket Option Linger Graceful Hard Wait for Option Interval Close Close Close Close SO_LINGER don't care SO_LINGER zero SO_LINGER nonzero 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.
  • Page 70: So_Rcvlowat

    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.
  • Page 71 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. Chapter 3...
  • Page 72: Synchronous I/O Multiplexing With Select

    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.
  • Page 73 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.
  • Page 74 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 */ Chapter 3...
  • Page 75: Sending And Receiving Data Asynchronously

    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.
  • Page 76 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.
  • Page 77: Nonblocking I/O

    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 <sys/ioctl.h>...
  • Page 78: Using Shutdown

    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.
  • Page 79: When To Shut Down A Socket

    Advanced Topics for Stream Sockets Using Shutdown Description of Parameter INPUT Value Contents socket descriptor socket descriptor of socket to be shut down number that indicates 0, 1 or 2 the type of shutdown Function result: 0 if shutdown is successful, –1 if failure occurs. Example: shutdown (s, 1);...
  • Page 80: Using Read And Write To Make Stream Sockets Transparent

    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.
  • Page 81: Sending And Receiving Out-Of-Band Data

    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.
  • Page 82 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.
  • Page 83 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.
  • Page 84 Advanced Topics for Stream Sockets Sending and Receiving Out-of-band Data printf(”received %c OOB\n”, mark); return; Chapter 3...
  • Page 85: Using Internet Datagram Sockets

    Using Internet Datagram Sockets This chapter describes communication between processes using internet datagram sockets.
  • Page 86: Overview

    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.
  • Page 87 Using Internet Datagram Sockets Overview Table 4-1 Exchanging Data Between Internet Datagram Sockets Client System Server Process System Call Process Call Used Activity Used Activity create a socket create a socket socket() socket() bind a socket bind a socket bind() bind() address address...
  • Page 88: Preparing Address Variables

    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: •...
  • Page 89: Getting The Remote Host's Network Address

    Using Internet Datagram Sockets Preparing Address Variables Field Description Specifies the address family and should short sin_family always be set to AF_INET. Specifies the port address. Assign this field u_short sin_port when you bind the port address for the socket or when you get a port address for a specific service.
  • Page 90: Getting The Port Address For The Desired Service

    Using Internet Datagram Sockets Preparing Address Variables #include <netdb.h> 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.
  • Page 91: Using A Wildcard Local Address

    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.
  • Page 92: Writing The Server And Client Processes

    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 <sys/types.h>...
  • Page 93: Binding Socket Addresses To Datagram Sockets

    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...
  • Page 94 Using Internet Datagram Sockets Writing the Server and Client Processes Parameter Description of Contents INPUT Value socket descriptor of local socket descriptor of socket 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...
  • Page 95: Sending And Receiving Messages

    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.
  • Page 96: Receiving 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) address of recipient socket pointer to the socket address that message should be sent to tolen size of to length of address...
  • Page 97 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.
  • Page 98: Flag Options

    Using Internet Datagram Sockets Sending and Receiving Messages OUTPUT Parameter Contents INPUT Value Value flags settings for 0 or MSG_PEEK unchanged optional flags from address of pointer to address pointer to socket that structure, not used socket sent message for input address of socket that sent the...
  • Page 99 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.
  • Page 100: Closing A Socket

    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.
  • Page 101: 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.
  • Page 102 Using Internet Datagram Sockets Example Using Datagram Sockets #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <netdb.h> int s; /* socket descriptor */ #define BUFFERSIZE 1024 /* max size of packets to be received */ int cc; /* contains the number of bytes read */ char buffer[BUFFERSIZE];...
  • Page 103 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]);...
  • Page 104 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().
  • Page 105 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.
  • Page 106 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.
  • Page 107 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]);...
  • Page 108 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.
  • Page 109: Advanced Topics For Internet Datagram Sockets

    Advanced Topics for Internet Datagram Sockets This chapter explains the following:...
  • Page 110 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. Chapter 5...
  • Page 111: So_Broadcast Socket Option

    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. Chapter 5...
  • Page 112: Specifying A Default Socket Address

    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.
  • Page 113: When To Specify A Default Socket Address

    Advanced Topics for Internet Datagram Sockets Specifying a Default Socket Address Include files: #include<sys/types.h> #include<netinet/in.h> #include<sys/socket.h> System call: connect(s,addr,addrlen) int s; struct sockaddr*addr; int addrlen; Description of Parameter INPUT Value Contents socket descriptor of local socket descriptor of socket socket requesting default peer address addr...
  • Page 114: Synchronous I/O Multiplexing With Select

    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.
  • Page 115: Sending And Receiving Data Asynchronously

    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.
  • Page 116: Sending And Receiving Ip Multicast Datagrams

    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.
  • Page 117 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.
  • Page 118: Receiving Ip Multicast Datagrams

    Advanced Topics for Internet Datagram Sockets Sending and Receiving IP Multicast Datagrams #include <netinet/in.h> 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.
  • Page 119 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.
  • Page 120 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.
  • Page 121: Nonblocking I/O

    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<sys/ioctl.h>...
  • Page 122: Using Broadcast Addresses

    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.
  • Page 123: Using Unix Domain Stream Sockets

    Using UNIX Domain Stream Sockets This chapter describes creating a UNIX Domain stream socket connection between two processes executing on the same node.
  • Page 124: Overview

    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.
  • Page 125 Using UNIX Domain Stream Sockets Overview Client System Server Process System Call Process Call Used Activity Used Activity send data write() or send() receive data read() or recv() disconnect disconnect socket shutdown() shutdown() socket or close() (optional) or close() (optional) Each of these steps or activities is described in more detail in the following sections.
  • Page 126: Preparing Address Variables

    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. •...
  • Page 127 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. Chapter 6...
  • Page 128: Writing The Server Process

    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.
  • Page 129: Binding A Socket Address To The Server Process's Socket

    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.
  • Page 130: Setting The Server Up To Wait For Connection Requests

    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 ).
  • Page 131: Accepting A Connection

    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: •...
  • Page 132 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.
  • Page 133: Writing The Client Process

    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.
  • Page 134: Requesting A Connection

    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 <sys/types.h>...
  • Page 135 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. Chapter 6...
  • Page 136: Sending And Receiving Data

    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.
  • Page 137: Receiving Data

    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.
  • Page 138: Flag Options

    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.
  • Page 139: Closing A Socket

    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.
  • Page 140: Example Using Unix Domain Stream Sockets

    These programs are provided as examples only of UNIX Domain stream NOTE 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.
  • Page 141 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);...
  • Page 142 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”);...
  • Page 143 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;...
  • Page 144 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.
  • Page 145 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.
  • Page 146 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);...
  • Page 147: Using Unix Domain Datagram Sockets

    Using UNIX Domain Datagram Sockets This chapter describes communication between processes using UNIX Domain datagram sockets.
  • Page 148: Overview

    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.
  • Page 149 Using UNIX Domain Datagram Sockets Overview Table 7-1 Exchanging Data Between UNIX Domain Datagram Sockets Client System Server Process System Call Process Call Used Activity Used Activity create a socket create a socket socket() socket() bind a socket bind a socket bind() bind() send message...
  • Page 150: Preparing Address Variables

    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: •...
  • Page 151 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.
  • Page 152: Writing The Server And Client Processes

    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.
  • Page 153: Binding Socket Addresses To Unix Domain Datagram Sockets

    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.
  • Page 154 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.
  • Page 155: Sending And Receiving Messages

    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.
  • Page 156: Receiving Messages

    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.
  • Page 157 Using UNIX Domain Datagram Sockets Sending and Receiving Messages OUTPUT Parameter Contents INPUT Value Value socket socket descriptor unchanged descriptor of of socket receiving local socket the message pointer to data pointer to buffer pointer to buffer that is to receive received data data maximum...
  • Page 158 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. Chapter 7...
  • Page 159: Closing A Socket

    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.
  • Page 160: Example Using Unix Domain Datagram Sockets

    These programs are provided as examples only of UNIX Domain NOTE 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.
  • Page 161 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));...
  • Page 162 Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/un.h> #include <stdio.h> #include <signal.h> #include <netdb.h> #define SOCKET_PATH “/tmp/myserver” #define SOCKET_PATHCLNT “/tmp/my_af_unix_client” #define bzero(ptr, len) memset((ptr), NULL, (len)) timeout(); main() sock; j, slen, rlen;...
  • Page 163 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.sun_path, SOCKET_PATH); for (j = 0; j < 5; j++) { sleep(1); slen = sendto(sock, sdata, 2000, 0, (struct sockaddr *) &servaddr, sizeof(servaddr));...
  • Page 164 Using UNIX Domain Datagram Sockets Example Using UNIX Domain Datagram Sockets Chapter 7...
  • Page 165: Programming Hints

    Programming Hints This chapter contains information for: • Troubleshooting. • Using diagnostic utilities as troubleshooting tools.
  • Page 166 Programming Hints • Adding a server process to the internet daemon. • Summary tables for system and library calls. • Portability issues. Chapter 8...
  • Page 167: Troubleshooting

    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);...
  • Page 168: Using Diagnostic Utilities As Troubleshooting Tools

    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. Use ping to verify the physical connection with the ping destination node.
  • Page 169: Adding A Server Process To The Internet Daemon

    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:...
  • Page 170 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.
  • Page 171 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.
  • Page 172 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);...
  • Page 173: Summary Tables For System And Library Calls

    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 Creates a socket, or communication endpoint for the socket calling process.
  • Page 174 Programming Hints Summary Tables for System and Library Calls System Call Description Gets the socket address of the specified socket. getsockname Gets, or sets, the options associated with a socket. getsockopt, setsockopt Gets the name of the peer socket connected to the getpeername specified socket.
  • Page 175 Programming Hints Summary Tables for System and Library Calls System Call Description Can be used to improve efficiency for a process that select accesses multiple sockets or other I/O devices simultaneously. Refer to the sections on “Synchronous I/O Multiplexing with Select.” Can be used for finding the number of receivable ioctl bytes with FIONREAD and for setting the...
  • Page 176 Programming Hints Summary Tables for System and Library Calls Table 8-3 Library Calls Library Call Description internet address manipulation routines inet_addr inet_lnaof inet_makeaddr inet_netof inet_network get or set service entry setservent endservent getservbyname getservbyport getservent get or set protocol entry setprotoent endprotoent getprotobyname...
  • Page 177: Portability Issues

    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.
  • Page 178 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()
  • Page 179 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 HP- UX systems, but they do have HP-UX equivalents.
  • Page 180 Programming Hints Portability Issues Chapter 8...
  • Page 181: Bsd Sockets Quick Reference Table

    BSD Sockets Quick Reference Table This appendix compares HP-UX BSD Sockets and X/Open Sockets.
  • Page 182: Quick Reference Table

    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”...
  • Page 183 BSD Sockets Quick Reference Table Quick Reference Table HP-UX X/Open getpeername getpeername int getpeername (int socket, void int getpeername (int socket, struct *address, int *address_len); sockaddr *address, size_t *address_len); getsockname getsockname int getsockname (int socket, void int getsockname (int socket, struct *address, int *address_len);...
  • Page 184 BSD Sockets Quick Reference Table Quick Reference Table HP-UX X/Open recvmsg recvmsg int recvmsg (int socket, struct msghdr ssize_t recvmsg (int socket, struct msg[], int flags); msghdr *msg, int flags); select select int select (int nfds, fd_set *readfds, int select (int nfds, fd_set *readfds, fd_set fd_set *writefds, fd_set *errorfds, struct *writefds, fd_set *errorfds, struct timeval timeval *timeout);...
  • Page 185 BSD Sockets Quick Reference Table Quick Reference Table HP-UX X/Open socketpair socketpair int socketpair (int af, int type, int int socketpair (int domain, int type, int protocol, int sv[2]); protocol, int socketvector[2]); write(2) write(2) ssize_t write (int fildes, const void *buf, ssize_t write (int fildes, const void *buf, size_t nbyte);...
  • Page 186 BSD Sockets Quick Reference Table Quick Reference Table Appendix A...
  • Page 187 Glossary The address Address family: ARPA/Berkeley Services: format used to interpret The set of services originally addresses specified in socket developed for use on the operations. The internet ARPANET (i.e., telnet(1)) or address family (AF_INET) is distributed with the Berkeley supported.
  • Page 188 Glossary UNIX software released by the pair of sockets at either end of University of California at the connection. Berkeley. See also, “Association.” Binding: Establishing the Daemon: A software process address of a socket which that runs continuously and allows other sockets to connect provides services on request.
  • Page 189 Glossary services. Organization: Called “ISO,” this organization created a Domain: A set of allowable network model that identifies names or values. See also, the seven commonly-used “Communication domain.” protocol levels for networking. File Transfer Protocol: The Internet: All ARPA networks file transfer protocol that is that are registered with the traditionally used in ARPA...
  • Page 190 Glossary IPC: transmitted between processes. See Interprocess Communication. Also called a “frame.” ISO: See International Standards Peer: An Interprocess Organization. Communication socket at the other end of a connection. Link-level address: A six- byte quantity that is distinct Port: An address within a host from the internet address and that is used to differentiate is the unique address of the...
  • Page 191 Glossary Socket: Addressable entities sequence sent. Stream sockets that are at either end of an use the TCP protocol. Interprocess Communication TCP: connection. A socket is See Transmission Control Protocol. identified by a socket descriptor. A program can write Telnet: A virtual terminal data to and read data from a protocol traditionally used on socket, just as it writes and...
  • Page 192 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.
  • Page 193 Index domain stream sockets getsockname Internet stream sockets getsockopt accept SO_REUSEADDR getwd domain stream sockets specifying default socket address Internet stream sockets summary table htonl nonblocking I/O htons pending connections summary table datagram sockets address conversion call index addressing domain inet AF_INET inet_addr...
  • Page 194 Index BSD IPC connections LINGER options SO_DONTROUTE BSD IPC system calls listensbacklogparameter" SO_KEEPALIVE using datagram message SO_LINGER sockets MSG_OOB SO_RCVBUF channel MSG_PEEK SO_REUSEADDR client nonblocking I/O SO_SNDBUF client-server model nondestructive read sockaddr closing a socket other system calls sockaddr_in out of band data socket address communication domain out-of-band data...
  • Page 195 Index preparing address variables specifying default socket address O_NDELAY sockaddr_un summary table O_NONBLOCK ioctl rindex out of band data IP multicasting IP_ADD_MEMBERSHIP IP_DROP_MEMBERSHIP select packet IP_MAX_MEMBERSHIPS send pathname IP_MULTICAST_IF domain stream sockets peer IP_MULTICAST_LOOP perror IP_MULTICAST_TTL Internet datagram sockets ping IPC connections Internet stream sockets port...
  • Page 196 Index SO_KEEPALIVE Internet datagram sockets SO_LINGER Internet stream sockets SO_OOBINLINE SO_RCVBUF nonblocking I/O SO_RCVLOWAT specifying default socket SO_RCVTIMEO address SO_REUSEADDR summary table SO_REUSEPORT SO_SNDBUF SO_SNDLOWAT SO_SNDTIMEO SO_TYPE SO_USELOOPBACK socket domain datagram sockets socket address sockets sprintf strchr stream sockets strrchr synchronous signals sockets...

Table of Contents