   This file documents the GNU C library.

   This is Edition 0.08 DRAFT, last updated 11 Jan 1999, of `The GNU C
Library Reference Manual', for Version 2.1 Beta.

   Copyright (C) 1993, '94, '95, '96, '97, '98, '99 Free Software
Foundation, Inc.

   Permission is granted to make and distribute verbatim copies of this
manual provided the copyright notice and this permission notice are
preserved on all copies.

   Permission is granted to copy and distribute modified versions of
this manual under the conditions for verbatim copying, provided also
that the section entitled "GNU Library General Public License" is
included exactly as in the original, and provided that the entire
resulting derived work is distributed under the terms of a permission
notice identical to this one.

   Permission is granted to copy and distribute translations of this
manual into another language, under the above conditions for modified
versions, except that the text of the translation of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.

The Services Database
---------------------

   The database that keeps track of "well-known" services is usually
either the file `/etc/services' or an equivalent from a name server.
You can use these utilities, declared in `netdb.h', to access the
services database.

 - Data Type: struct servent
     This data type holds information about entries from the services
     database.  It has the following members:

    `char *s_name'
          This is the "official" name of the service.

    `char **s_aliases'
          These are alternate names for the service, represented as an
          array of strings.  A null pointer terminates the array.

    `int s_port'
          This is the port number for the service.  Port numbers are
          given in network byte order; see Byte Order.

    `char *s_proto'
          This is the name of the protocol to use with this service.
          See Protocols Database.

   To get information about a particular service, use the
`getservbyname' or `getservbyport' functions.  The information is
returned in a statically-allocated structure; you must copy the
information if you need to save it across calls.

 - Function: struct servent * getservbyname (const char *NAME, const
          char *PROTO)
     The `getservbyname' function returns information about the service
     named NAME using protocol PROTO.  If it can't find such a service,
     it returns a null pointer.

     This function is useful for servers as well as for clients; servers
     use it to determine which port they should listen on (see
     Listening).

 - Function: struct servent * getservbyport (int PORT, const char
          *PROTO)
     The `getservbyport' function returns information about the service
     at port PORT using protocol PROTO.  If it can't find such a
     service, it returns a null pointer.

You can also scan the services database using `setservent',
`getservent', and `endservent'.  Be careful in using these functions,
because they are not reentrant.

 - Function: void setservent (int STAYOPEN)
     This function opens the services database to begin scanning it.

     If the STAYOPEN argument is nonzero, this sets a flag so that
     subsequent calls to `getservbyname' or `getservbyport' will not
     close the database (as they usually would).  This makes for more
     efficiency if you call those functions several times, by avoiding
     reopening the database for each call.

 - Function: struct servent * getservent (void)
     This function returns the next entry in the services database.  If
     there are no more entries, it returns a null pointer.

 - Function: void endservent (void)
     This function closes the services database.

Byte Order Conversion
---------------------

   Different kinds of computers use different conventions for the
ordering of bytes within a word.  Some computers put the most
significant byte within a word first (this is called "big-endian"
order), and others put it last ("little-endian" order).

   So that machines with different byte order conventions can
communicate, the Internet protocols specify a canonical byte order
convention for data transmitted over the network.  This is known as the
"network byte order".

   When establishing an Internet socket connection, you must make sure
that the data in the `sin_port' and `sin_addr' members of the
`sockaddr_in' structure are represented in the network byte order.  If
you are encoding integer data in the messages sent through the socket,
you should convert this to network byte order too.  If you don't do
this, your program may fail when running on or talking to other kinds
of machines.

   If you use `getservbyname' and `gethostbyname' or `inet_addr' to get
the port number and host address, the values are already in the network
byte order, and you can copy them directly into the `sockaddr_in'
structure.

   Otherwise, you have to convert the values explicitly.  Use `htons'
and `ntohs' to convert values for the `sin_port' member.  Use `htonl'
and `ntohl' to convert IPv4 addresses for the `sin_addr' member.
(Remember, `struct in_addr' is equivalent to `uint32_t'.)  These
functions are declared in `netinet/in.h'.

 - Function: uint16_t htons (uint16_t HOSTSHORT)
     This function converts the `uint16_t' integer HOSTSHORT from host
     byte order to network byte order.

 - Function: uint16_t ntohs (uint16_t NETSHORT)
     This function converts the `uint16_t' integer NETSHORT from
     network byte order to host byte order.

 - Function: uint32_t htonl (uint32_t HOSTLONG)
     This function converts the `uint32_t' integer HOSTLONG from host
     byte order to network byte order.

     This is used for IPv4 internet addresses.

 - Function: uint32_t ntohl (uint32_t NETLONG)
     This function converts the `uint32_t' integer NETLONG from network
     byte order to host byte order.

     This is used for IPv4 internet addresses.

Protocols Database
------------------

   The communications protocol used with a socket controls low-level
details of how data is exchanged.  For example, the protocol implements
things like checksums to detect errors in transmissions, and routing
instructions for messages.  Normal user programs have little reason to
mess with these details directly.

   The default communications protocol for the Internet namespace
depends on the communication style.  For stream communication, the
default is TCP ("transmission control protocol").  For datagram
communication, the default is UDP ("user datagram protocol").  For
reliable datagram communication, the default is RDP ("reliable datagram
protocol").  You should nearly always use the default.

   Internet protocols are generally specified by a name instead of a
number.  The network protocols that a host knows about are stored in a
database.  This is usually either derived from the file
`/etc/protocols', or it may be an equivalent provided by a name server.
You look up the protocol number associated with a named protocol in
the database using the `getprotobyname' function.

   Here are detailed descriptions of the utilities for accessing the
protocols database.  These are declared in `netdb.h'.

 - Data Type: struct protoent
     This data type is used to represent entries in the network
     protocols database.  It has the following members:

    `char *p_name'
          This is the official name of the protocol.

    `char **p_aliases'
          These are alternate names for the protocol, specified as an
          array of strings.  The last element of the array is a null
          pointer.

    `int p_proto'
          This is the protocol number (in host byte order); use this
          member as the PROTOCOL argument to `socket'.

   You can use `getprotobyname' and `getprotobynumber' to search the
protocols database for a specific protocol.  The information is
returned in a statically-allocated structure; you must copy the
information if you need to save it across calls.

 - Function: struct protoent * getprotobyname (const char *NAME)
     The `getprotobyname' function returns information about the
     network protocol named NAME.  If there is no such protocol, it
     returns a null pointer.

 - Function: struct protoent * getprotobynumber (int PROTOCOL)
     The `getprotobynumber' function returns information about the
     network protocol with number PROTOCOL.  If there is no such
     protocol, it returns a null pointer.

   You can also scan the whole protocols database one protocol at a
time by using `setprotoent', `getprotoent', and `endprotoent'.  Be
careful in using these functions, because they are not reentrant.

 - Function: void setprotoent (int STAYOPEN)
     This function opens the protocols database to begin scanning it.

     If the STAYOPEN argument is nonzero, this sets a flag so that
     subsequent calls to `getprotobyname' or `getprotobynumber' will
     not close the database (as they usually would).  This makes for
     more efficiency if you call those functions several times, by
     avoiding reopening the database for each call.

 - Function: struct protoent * getprotoent (void)
     This function returns the next entry in the protocols database.  It
     returns a null pointer if there are no more entries.

 - Function: void endprotoent (void)
     This function closes the protocols database.

Internet Socket Example
-----------------------

   Here is an example showing how to create and name a socket in the
Internet namespace.  The newly created socket exists on the machine that
the program is running on.  Rather than finding and using the machine's
Internet address, this example specifies `INADDR_ANY' as the host
address; the system replaces that with the machine's actual address.

     #include <stdio.h>
     #include <stdlib.h>
     #include <sys/socket.h>
     #include <netinet/in.h>

     int
     make_socket (uint16_t port)
     {
       int sock;
       struct sockaddr_in name;

       /* Create the socket. */
       sock = socket (PF_INET, SOCK_STREAM, 0);
       if (sock < 0)
         {
           perror ("socket");
           exit (EXIT_FAILURE);
         }

       /* Give the socket a name. */
       name.sin_family = AF_INET;
       name.sin_port = htons (port);
       name.sin_addr.s_addr = htonl (INADDR_ANY);
       if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
         {
           perror ("bind");
           exit (EXIT_FAILURE);
         }

       return sock;
     }

   Here is another example, showing how you can fill in a `sockaddr_in'
structure, given a host name string and a port number:

     #include <stdio.h>
     #include <stdlib.h>
     #include <sys/socket.h>
     #include <netinet/in.h>
     #include <netdb.h>

     void
     init_sockaddr (struct sockaddr_in *name,
                    const char *hostname,
                    uint16_t port)
     {
       struct hostent *hostinfo;

       name->sin_family = AF_INET;
       name->sin_port = htons (port);
       hostinfo = gethostbyname (hostname);
       if (hostinfo == NULL)
         {
           fprintf (stderr, "Unknown host %s.\n", hostname);
           exit (EXIT_FAILURE);
         }
       name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
     }

Other Namespaces
================

   Certain other namespaces and associated protocol families are
supported but not documented yet because they are not often used.
`PF_NS' refers to the Xerox Network Software protocols.  `PF_ISO' stands
for Open Systems Interconnect.  `PF_CCITT' refers to protocols from
CCITT.  `socket.h' defines these symbols and others naming protocols
not actually implemented.

   `PF_IMPLINK' is used for communicating between hosts and Internet
Message Processors.  For information on this, and on `PF_ROUTE', an
occasionally-used local area routing protocol, see the GNU Hurd Manual
(to appear in the future).

Opening and Closing Sockets
===========================

   This section describes the actual library functions for opening and
closing sockets.  The same functions work for all namespaces and
connection styles.

Creating a Socket
-----------------

   The primitive for creating a socket is the `socket' function,
declared in `sys/socket.h'.

 - Function: int socket (int NAMESPACE, int STYLE, int PROTOCOL)
     This function creates a socket and specifies communication style
     STYLE, which should be one of the socket styles listed in
     Communication Styles.  The NAMESPACE argument specifies the
     namespace; it must be `PF_LOCAL' (see Local Namespace) or
     `PF_INET' (see Internet Namespace).  PROTOCOL designates the
     specific protocol (see Socket Concepts); zero is usually right
     for PROTOCOL.

     The return value from `socket' is the file descriptor for the new
     socket, or `-1' in case of error.  The following `errno' error
     conditions are defined for this function:

    `EPROTONOSUPPORT'
          The PROTOCOL or STYLE is not supported by the NAMESPACE
          specified.

    `EMFILE'
          The process already has too many file descriptors open.

    `ENFILE'
          The system already has too many file descriptors open.

    `EACCESS'
          The process does not have privilege to create a socket of the
          specified STYLE or PROTOCOL.

    `ENOBUFS'
          The system ran out of internal buffer space.

     The file descriptor returned by the `socket' function supports both
     read and write operations.  But, like pipes, sockets do not
     support file positioning operations.

   For examples of how to call the `socket' function, see Local Socket Example,
or Inet Example.

Closing a Socket
----------------

   When you are finished using a socket, you can simply close its file
descriptor with `close'; see Opening and Closing Files.  If
there is still data waiting to be transmitted over the connection,
normally `close' tries to complete this transmission.  You can control
this behavior using the `SO_LINGER' socket option to specify a timeout
period; see Socket Options.

   You can also shut down only reception or only transmission on a
connection by calling `shutdown', which is declared in `sys/socket.h'.

 - Function: int shutdown (int SOCKET, int HOW)
     The `shutdown' function shuts down the connection of socket
     SOCKET.  The argument HOW specifies what action to perform:

    `0'
          Stop receiving data for this socket.  If further data arrives,
          reject it.

    `1'
          Stop trying to transmit data from this socket.  Discard any
          data waiting to be sent.  Stop looking for acknowledgement of
          data already sent; don't retransmit it if it is lost.

    `2'
          Stop both reception and transmission.

     The return value is `0' on success and `-1' on failure.  The
     following `errno' error conditions are defined for this function:

    `EBADF'
          SOCKET is not a valid file descriptor.

    `ENOTSOCK'
          SOCKET is not a socket.

    `ENOTCONN'
          SOCKET is not connected.

Socket Pairs
------------

   A "socket pair" consists of a pair of connected (but unnamed)
sockets.  It is very similar to a pipe and is used in much the same
way.  Socket pairs are created with the `socketpair' function, declared
in `sys/socket.h'.  A socket pair is much like a pipe; the main
difference is that the socket pair is bidirectional, whereas the pipe
has one input-only end and one output-only end (see Pipes and FIFOs).

 - Function: int socketpair (int NAMESPACE, int STYLE, int PROTOCOL,
          int FILEDES[2])
     This function creates a socket pair, returning the file
     descriptors in `FILEDES[0]' and `FILEDES[1]'.  The socket pair is
     a full-duplex communications channel, so that both reading and
     writing may be performed at either end.

     The NAMESPACE, STYLE, and PROTOCOL arguments are interpreted as
     for the `socket' function.  STYLE should be one of the
     communication styles listed in Communication Styles.  The
     NAMESPACE argument specifies the namespace, which must be
     `AF_LOCAL' (see Local Namespace); PROTOCOL specifies the
     communications protocol, but zero is the only meaningful value.

     If STYLE specifies a connectionless communication style, then the
     two sockets you get are not _connected_, strictly speaking, but
     each of them knows the other as the default destination address,
     so they can send packets to each other.

     The `socketpair' function returns `0' on success and `-1' on
     failure.  The following `errno' error conditions are defined for
     this function:

    `EMFILE'
          The process has too many file descriptors open.

    `EAFNOSUPPORT'
          The specified namespace is not supported.

    `EPROTONOSUPPORT'
          The specified protocol is not supported.

    `EOPNOTSUPP'
          The specified protocol does not support the creation of
          socket pairs.

Using Sockets with Connections
==============================

   The most common communication styles involve making a connection to a
particular other socket, and then exchanging data with that socket over
and over.  Making a connection is asymmetric; one side (the "client")
acts to request a connection, while the other side (the "server") makes
a socket and waits for the connection request.

Making a Connection
-------------------

   In making a connection, the client makes a connection while the
server waits for and accepts the connection.  Here we discuss what the
client program must do, using the `connect' function, which is declared
in `sys/socket.h'.

 - Function: int connect (int SOCKET, struct sockaddr *ADDR, socklen_t
          LENGTH)
     The `connect' function initiates a connection from the socket with
     file descriptor SOCKET to the socket whose address is specified by
     the ADDR and LENGTH arguments.  (This socket is typically on
     another machine, and it must be already set up as a server.)
     See Socket Addresses, for information about how these
     arguments are interpreted.

     Normally, `connect' waits until the server responds to the request
     before it returns.  You can set nonblocking mode on the socket
     SOCKET to make `connect' return immediately without waiting for
     the response.  See File Status Flags, for information about
     nonblocking mode.

     The normal return value from `connect' is `0'.  If an error
     occurs, `connect' returns `-1'.  The following `errno' error
     conditions are defined for this function:

    `EBADF'
          The socket SOCKET is not a valid file descriptor.

    `ENOTSOCK'
          File descriptor SOCKET is not a socket.

    `EADDRNOTAVAIL'
          The specified address is not available on the remote machine.

    `EAFNOSUPPORT'
          The namespace of the ADDR is not supported by this socket.

    `EISCONN'
          The socket SOCKET is already connected.

    `ETIMEDOUT'
          The attempt to establish the connection timed out.

    `ECONNREFUSED'
          The server has actively refused to establish the connection.

    `ENETUNREACH'
          The network of the given ADDR isn't reachable from this host.

    `EADDRINUSE'
          The socket address of the given ADDR is already in use.

    `EINPROGRESS'
          The socket SOCKET is non-blocking and the connection could
          not be established immediately.  You can determine when the
          connection is completely established with `select'; see
          Waiting for I/O.  Another `connect' call on the same
          socket, before the connection is completely established, will
          fail with `EALREADY'.

    `EALREADY'
          The socket SOCKET is non-blocking and already has a pending
          connection in progress (see `EINPROGRESS' above).

     This function is defined as a cancelation point in multi-threaded
     programs.  So one has to be prepared for this and make sure that
     possibly allocated resources (like memory, files descriptors,
     semaphores or whatever) are freed even if the thread is canceled.

Listening for Connections
-------------------------

   Now let us consider what the server process must do to accept
connections on a socket.  First it must use the `listen' function to
enable connection requests on the socket, and then accept each incoming
connection with a call to `accept' (see Accepting Connections).
Once connection requests are enabled on a server socket, the `select'
function reports when the socket has a connection ready to be accepted
(see Waiting for I/O).

   The `listen' function is not allowed for sockets using
connectionless communication styles.

   You can write a network server that does not even start running
until a connection to it is requested.  See Inetd Servers.

   In the Internet namespace, there are no special protection mechanisms
for controlling access to connect to a port; any process on any machine
can make a connection to your server.  If you want to restrict access to
your server, make it examine the addresses associated with connection
requests or implement some other handshaking or identification protocol.

   In the local namespace, the ordinary file protection bits control
who has access to connect to the socket.

 - Function: int listen (int SOCKET, unsigned int N)
     The `listen' function enables the socket SOCKET to accept
     connections, thus making it a server socket.

     The argument N specifies the length of the queue for pending
     connections.  When the queue fills, new clients attempting to
     connect fail with `ECONNREFUSED' until the server calls `accept' to
     accept a connection from the queue.

     The `listen' function returns `0' on success and `-1' on failure.
     The following `errno' error conditions are defined for this
     function:

    `EBADF'
          The argument SOCKET is not a valid file descriptor.

    `ENOTSOCK'
          The argument SOCKET is not a socket.

    `EOPNOTSUPP'
          The socket SOCKET does not support this operation.

Accepting Connections
---------------------

   When a server receives a connection request, it can complete the
connection by accepting the request.  Use the function `accept' to do
this.

   A socket that has been established as a server can accept connection
requests from multiple clients.  The server's original socket _does not
become part_ of the connection; instead, `accept' makes a new socket
which participates in the connection.  `accept' returns the descriptor
for this socket.  The server's original socket remains available for
listening for further connection requests.

   The number of pending connection requests on a server socket is
finite.  If connection requests arrive from clients faster than the
server can act upon them, the queue can fill up and additional requests
are refused with a `ECONNREFUSED' error.  You can specify the maximum
length of this queue as an argument to the `listen' function, although
the system may also impose its own internal limit on the length of this
queue.

 - Function: int accept (int SOCKET, struct sockaddr *ADDR, socklen_t
          *LENGTH_PTR)
     This function is used to accept a connection request on the server
     socket SOCKET.

     The `accept' function waits if there are no connections pending,
     unless the socket SOCKET has nonblocking mode set.  (You can use
     `select' to wait for a pending connection, with a nonblocking
     socket.)  See File Status Flags, for information about
     nonblocking mode.

     The ADDR and LENGTH-PTR arguments are used to return information
     about the name of the client socket that initiated the connection.
     See Socket Addresses, for information about the format of the
     information.

     Accepting a connection does not make SOCKET part of the
     connection.  Instead, it creates a new socket which becomes
     connected.  The normal return value of `accept' is the file
     descriptor for the new socket.

     After `accept', the original socket SOCKET remains open and
     unconnected, and continues listening until you close it.  You can
     accept further connections with SOCKET by calling `accept' again.

     If an error occurs, `accept' returns `-1'.  The following `errno'
     error conditions are defined for this function:

    `EBADF'
          The SOCKET argument is not a valid file descriptor.

    `ENOTSOCK'
          The descriptor SOCKET argument is not a socket.

    `EOPNOTSUPP'
          The descriptor SOCKET does not support this operation.

    `EWOULDBLOCK'
          SOCKET has nonblocking mode set, and there are no pending
          connections immediately available.

     This function is defined as a cancelation point in multi-threaded
     programs.  So one has to be prepared for this and make sure that
     possibly allocated resources (like memory, files descriptors,
     semaphores or whatever) are freed even if the thread is canceled.

   The `accept' function is not allowed for sockets using
connectionless communication styles.

Who is Connected to Me?
-----------------------

 - Function: int getpeername (int SOCKET, struct sockaddr *ADDR,
          socklen_t *LENGTH-PTR)
     The `getpeername' function returns the address of the socket that
     SOCKET is connected to; it stores the address in the memory space
     specified by ADDR and LENGTH-PTR.  It stores the length of the
     address in `*LENGTH-PTR'.

     See Socket Addresses, for information about the format of the
     address.  In some operating systems, `getpeername' works only for
     sockets in the Internet domain.

     The return value is `0' on success and `-1' on error.  The
     following `errno' error conditions are defined for this function:

    `EBADF'
          The argument SOCKET is not a valid file descriptor.

    `ENOTSOCK'
          The descriptor SOCKET is not a socket.

    `ENOTCONN'
          The socket SOCKET is not connected.

    `ENOBUFS'
          There are not enough internal buffers available.

Transferring Data
-----------------

   Once a socket has been connected to a peer, you can use the ordinary
`read' and `write' operations (see I/O Primitives) to transfer
data.  A socket is a two-way communications channel, so read and write
operations can be performed at either end.

   There are also some I/O modes that are specific to socket operations.
In order to specify these modes, you must use the `recv' and `send'
functions instead of the more generic `read' and `write' functions.
The `recv' and `send' functions take an additional argument which you
can use to specify various flags to control the special I/O modes.  For
example, you can specify the `MSG_OOB' flag to read or write
out-of-band data, the `MSG_PEEK' flag to peek at input, or the
`MSG_DONTROUTE' flag to control inclusion of routing information on
output.

Sending Data
............

   The `send' function is declared in the header file `sys/socket.h'.
If your FLAGS argument is zero, you can just as well use `write'
instead of `send'; see I/O Primitives.  If the socket was
connected but the connection has broken, you get a `SIGPIPE' signal for
any use of `send' or `write' (see Miscellaneous Signals).

 - Function: int send (int SOCKET, void *BUFFER, size_t SIZE, int FLAGS)
     The `send' function is like `write', but with the additional flags
     FLAGS.  The possible values of FLAGS are described in Socket Data Options.

     This function returns the number of bytes transmitted, or `-1' on
     failure.  If the socket is nonblocking, then `send' (like `write')
     can return after sending just part of the data.  See File Status Flags,
     for information about nonblocking mode.

     Note, however, that a successful return value merely indicates that
     the message has been sent without error, not necessarily that it
     has been received without error.

     The following `errno' error conditions are defined for this
     function:

    `EBADF'
          The SOCKET argument is not a valid file descriptor.

    `EINTR'
          The operation was interrupted by a signal before any data was
          sent.  See Interrupted Primitives.

    `ENOTSOCK'
          The descriptor SOCKET is not a socket.

    `EMSGSIZE'
          The socket type requires that the message be sent atomically,
          but the message is too large for this to be possible.

    `EWOULDBLOCK'
          Nonblocking mode has been set on the socket, and the write
          operation would block.  (Normally `send' blocks until the
          operation can be completed.)

    `ENOBUFS'
          There is not enough internal buffer space available.

    `ENOTCONN'
          You never connected this socket.

    `EPIPE'
          This socket was connected but the connection is now broken.
          In this case, `send' generates a `SIGPIPE' signal first; if
          that signal is ignored or blocked, or if its handler returns,
          then `send' fails with `EPIPE'.

     This function is defined as a cancelation point in multi-threaded
     programs.  So one has to be prepared for this and make sure that
     possibly allocated resources (like memory, files descriptors,
     semaphores or whatever) are freed even if the thread is canceled.

Receiving Data
..............

   The `recv' function is declared in the header file `sys/socket.h'.
If your FLAGS argument is zero, you can just as well use `read' instead
of `recv'; see I/O Primitives.

 - Function: int recv (int SOCKET, void *BUFFER, size_t SIZE, int FLAGS)
     The `recv' function is like `read', but with the additional flags
     FLAGS.  The possible values of FLAGS are described in Socket Data Options.

     If nonblocking mode is set for SOCKET, and no data is available to
     be read, `recv' fails immediately rather than waiting.  See File Status Flags,
     for information about nonblocking mode.

     This function returns the number of bytes received, or `-1' on
     failure.  The following `errno' error conditions are defined for
     this function:

    `EBADF'
          The SOCKET argument is not a valid file descriptor.

    `ENOTSOCK'
          The descriptor SOCKET is not a socket.

    `EWOULDBLOCK'
          Nonblocking mode has been set on the socket, and the read
          operation would block.  (Normally, `recv' blocks until there
          is input available to be read.)

    `EINTR'
          The operation was interrupted by a signal before any data was
          read.  See Interrupted Primitives.

    `ENOTCONN'
          You never connected this socket.

     This function is defined as a cancelation point in multi-threaded
     programs.  So one has to be prepared for this and make sure that
     possibly allocated resources (like memory, files descriptors,
     semaphores or whatever) are freed even if the thread is canceled.

Socket Data Options
...................

   The FLAGS argument to `send' and `recv' is a bit mask.  You can
bitwise-OR the values of the following macros together to obtain a
value for this argument.  All are defined in the header file
`sys/socket.h'.

 - Macro: int MSG_OOB
     Send or receive out-of-band data.  See Out-of-Band Data.

 - Macro: int MSG_PEEK
     Look at the data but don't remove it from the input queue.  This is
     only meaningful with input functions such as `recv', not with
     `send'.

 - Macro: int MSG_DONTROUTE
     Don't include routing information in the message.  This is only
     meaningful with output operations, and is usually only of interest
     for diagnostic or routing programs.  We don't try to explain it
     here.

Byte Stream Socket Example
--------------------------

   Here is an example client program that makes a connection for a byte
stream socket in the Internet namespace.  It doesn't do anything
particularly interesting once it has connected to the server; it just
sends a text string to the server and exits.

   This program uses `init_sockaddr' to set up the socket address; see
Inet Example.

     #include <stdio.h>
     #include <errno.h>
     #include <stdlib.h>
     #include <unistd.h>
     #include <sys/types.h>
     #include <sys/socket.h>
     #include <netinet/in.h>
     #include <netdb.h>

     #define PORT            5555
     #define MESSAGE         "Yow!!! Are we having fun yet?!?"
     #define SERVERHOST      "mescaline.gnu.org"

     void
     write_to_server (int filedes)
     {
       int nbytes;

       nbytes = write (filedes, MESSAGE, strlen (MESSAGE) + 1);
       if (nbytes < 0)
         {
           perror ("write");
           exit (EXIT_FAILURE);
         }
     }

     int
     main (void)
     {
       extern void init_sockaddr (struct sockaddr_in *name,
                                  const char *hostname,
                                  uint16_t port);
       int sock;
       struct sockaddr_in servername;

       /* Create the socket. */
       sock = socket (PF_INET, SOCK_STREAM, 0);
       if (sock < 0)
         {
           perror ("socket (client)");
           exit (EXIT_FAILURE);
         }

       /* Connect to the server. */
       init_sockaddr (&servername, SERVERHOST, PORT);
       if (0 > connect (sock,
                        (struct sockaddr *) &servername,
                        sizeof (servername)))
         {
           perror ("connect (client)");
           exit (EXIT_FAILURE);
         }

       /* Send data to the server. */
       write_to_server (sock);
       close (sock);
       exit (EXIT_SUCCESS);
     }

Byte Stream Connection Server Example
-------------------------------------

   The server end is much more complicated.  Since we want to allow
multiple clients to be connected to the server at the same time, it
would be incorrect to wait for input from a single client by simply
calling `read' or `recv'.  Instead, the right thing to do is to use
`select' (see Waiting for I/O) to wait for input on all of the open
sockets.  This also allows the server to deal with additional
connection requests.

   This particular server doesn't do anything interesting once it has
gotten a message from a client.  It does close the socket for that
client when it detects an end-of-file condition (resulting from the
client shutting down its end of the connection).

   This program uses `make_socket' to set up the socket address; see
Inet Example.

     #include <stdio.h>
     #include <errno.h>
     #include <stdlib.h>
     #include <unistd.h>
     #include <sys/types.h>
     #include <sys/socket.h>
     #include <netinet/in.h>
     #include <netdb.h>

     #define PORT    5555
     #define MAXMSG  512

     int
     read_from_client (int filedes)
     {
       char buffer[MAXMSG];
       int nbytes;

       nbytes = read (filedes, buffer, MAXMSG);
       if (nbytes < 0)
         {
           /* Read error. */
           perror ("read");
           exit (EXIT_FAILURE);
         }
       else if (nbytes == 0)
         /* End-of-file. */
         return -1;
       else
         {
           /* Data read. */
           fprintf (stderr, "Server: got message: `%s'\n", buffer);
           return 0;
         }
     }

     int
     main (void)
     {
       extern int make_socket (uint16_t port);
       int sock;
       fd_set active_fd_set, read_fd_set;
       int i;
       struct sockaddr_in clientname;
       size_t size;

       /* Create the socket and set it up to accept connections. */
       sock = make_socket (PORT);
       if (listen (sock, 1) < 0)
         {
           perror ("listen");
           exit (EXIT_FAILURE);
         }

       /* Initialize the set of active sockets. */
       FD_ZERO (&active_fd_set);
       FD_SET (sock, &active_fd_set);

       while (1)
         {
           /* Block until input arrives on one or more active sockets. */
           read_fd_set = active_fd_set;
           if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0)
             {
               perror ("select");
               exit (EXIT_FAILURE);
             }

           /* Service all the sockets with input pending. */
           for (i = 0; i < FD_SETSIZE; ++i)
             if (FD_ISSET (i, &read_fd_set))
               {
                 if (i == sock)
                   {
                     /* Connection request on original socket. */
                     int new;
                     size = sizeof (clientname);
                     new = accept (sock,
                                   (struct sockaddr *) &clientname,
                                   &size);
                     if (new < 0)
                       {
                         perror ("accept");
                         exit (EXIT_FAILURE);
                       }
                     fprintf (stderr,
                              "Server: connect from host %s, port %hd.\n",
                              inet_ntoa (clientname.sin_addr),
                              ntohs (clientname.sin_port));
                     FD_SET (new, &active_fd_set);
                   }
                 else
                   {
                     /* Data arriving on an already-connected socket. */
                     if (read_from_client (i) < 0)
                       {
                         close (i);
                         FD_CLR (i, &active_fd_set);
                       }
                   }
               }
         }
     }

Out-of-Band Data
----------------

   Streams with connections permit "out-of-band" data that is delivered
with higher priority than ordinary data.  Typically the reason for
sending out-of-band data is to send notice of an exceptional condition.
The way to send out-of-band data is using `send', specifying the flag
`MSG_OOB' (see Sending Data).

   Out-of-band data is received with higher priority because the
receiving process need not read it in sequence; to read the next
available out-of-band data, use `recv' with the `MSG_OOB' flag (see
Receiving Data).  Ordinary read operations do not read out-of-band
data; they read only the ordinary data.

   When a socket finds that out-of-band data is on its way, it sends a
`SIGURG' signal to the owner process or process group of the socket.
You can specify the owner using the `F_SETOWN' command to the `fcntl'
function; see Interrupt Input.  You must also establish a
handler for this signal, as described in Signal Handling, in
order to take appropriate action such as reading the out-of-band data.

   Alternatively, you can test for pending out-of-band data, or wait
until there is out-of-band data, using the `select' function; it can
wait for an exceptional condition on the socket.  See Waiting for I/O,
for more information about `select'.

   Notification of out-of-band data (whether with `SIGURG' or with
`select') indicates that out-of-band data is on the way; the data may
not actually arrive until later.  If you try to read the out-of-band
data before it arrives, `recv' fails with an `EWOULDBLOCK' error.

   Sending out-of-band data automatically places a "mark" in the stream
of ordinary data, showing where in the sequence the out-of-band data
"would have been".  This is useful when the meaning of out-of-band data
is "cancel everything sent so far".  Here is how you can test, in the
receiving process, whether any ordinary data was sent before the mark:

     success = ioctl (socket, SIOCATMARK, &atmark);

   The `integer' variable ATMARK is set to a nonzero value if the
socket's read pointer has reached the "mark".

   Here's a function to discard any ordinary data preceding the
out-of-band mark:

     int
     discard_until_mark (int socket)
     {
       while (1)
         {
           /* This is not an arbitrary limit; any size will do.  */
           char buffer[1024];
           int atmark, success;

           /* If we have reached the mark, return.  */
           success = ioctl (socket, SIOCATMARK, &atmark);
           if (success < 0)
             perror ("ioctl");
           if (result)
             return;

           /* Otherwise, read a bunch of ordinary data and discard it.
              This is guaranteed not to read past the mark
              if it starts before the mark.  */
           success = read (socket, buffer, sizeof buffer);
           if (success < 0)
             perror ("read");
         }
     }

   If you don't want to discard the ordinary data preceding the mark,
you may need to read some of it anyway, to make room in internal system
buffers for the out-of-band data.  If you try to read out-of-band data
and get an `EWOULDBLOCK' error, try reading some ordinary data (saving
it so that you can use it when you want it) and see if that makes room.
Here is an example:

     struct buffer
     {
       char *buffer;
       int size;
       struct buffer *next;
     };

     /* Read the out-of-band data from SOCKET and return it
        as a `struct buffer', which records the address of the data
        and its size.

        It may be necessary to read some ordinary data
        in order to make room for the out-of-band data.
        If so, the ordinary data is saved as a chain of buffers
        found in the `next' field of the value.  */

     struct buffer *
     read_oob (int socket)
     {
       struct buffer *tail = 0;
       struct buffer *list = 0;

       while (1)
         {
           /* This is an arbitrary limit.
              Does anyone know how to do this without a limit?  */
           char *buffer = (char *) xmalloc (1024);
           int success;
           int atmark;

           /* Try again to read the out-of-band data.  */
           success = recv (socket, buffer, sizeof buffer, MSG_OOB);
           if (success >= 0)
             {
               /* We got it, so return it.  */
               struct buffer *link
                 = (struct buffer *) xmalloc (sizeof (struct buffer));
               link->buffer = buffer;
               link->size = success;
               link->next = list;
               return link;
             }

           /* If we fail, see if we are at the mark.  */
           success = ioctl (socket, SIOCATMARK, &atmark);
           if (success < 0)
             perror ("ioctl");
           if (atmark)
             {
               /* At the mark; skipping past more ordinary data cannot help.
                  So just wait a while.  */
               sleep (1);
               continue;
             }

           /* Otherwise, read a bunch of ordinary data and save it.
              This is guaranteed not to read past the mark
              if it starts before the mark.  */
           success = read (socket, buffer, sizeof buffer);
           if (success < 0)
             perror ("read");

           /* Save this data in the buffer list.  */
           {
             struct buffer *link
               = (struct buffer *) xmalloc (sizeof (struct buffer));
             link->buffer = buffer;
             link->size = success;

             /* Add the new link to the end of the list.  */
             if (tail)
               tail->next = link;
             else
               list = link;
             tail = link;
           }
         }
     }

Datagram Socket Operations
==========================

   This section describes how to use communication styles that don't use
connections (styles `SOCK_DGRAM' and `SOCK_RDM').  Using these styles,
you group data into packets and each packet is an independent
communication.  You specify the destination for each packet
individually.

   Datagram packets are like letters: you send each one independently,
with its own destination address, and they may arrive in the wrong
order or not at all.

   The `listen' and `accept' functions are not allowed for sockets
using connectionless communication styles.

Sending Datagrams
-----------------

   The normal way of sending data on a datagram socket is by using the
`sendto' function, declared in `sys/socket.h'.

   You can call `connect' on a datagram socket, but this only specifies
a default destination for further data transmission on the socket.
When a socket has a default destination, then you can use `send' (see
Sending Data) or even `write' (see I/O Primitives) to send a
packet there.  You can cancel the default destination by calling
`connect' using an address format of `AF_UNSPEC' in the ADDR argument.
See Connecting, for more information about the `connect' function.

 - Function: int sendto (int SOCKET, void *BUFFER. size_t SIZE, int
          FLAGS, struct sockaddr *ADDR, socklen_t LENGTH)
     The `sendto' function transmits the data in the BUFFER through the
     socket SOCKET to the destination address specified by the ADDR and
     LENGTH arguments.  The SIZE argument specifies the number of bytes
     to be transmitted.

     The FLAGS are interpreted the same way as for `send'; see
     Socket Data Options.

     The return value and error conditions are also the same as for
     `send', but you cannot rely on the system to detect errors and
     report them; the most common error is that the packet is lost or
     there is no one at the specified address to receive it, and the
     operating system on your machine usually does not know this.

     It is also possible for one call to `sendto' to report an error
     due to a problem related to a previous call.

     This function is defined as a cancelation point in multi-threaded
     programs.  So one has to be prepared for this and make sure that
     possibly allocated resources (like memory, files descriptors,
     semaphores or whatever) are freed even if the thread is canceled.