   This file documents the GNU C library.

   This is Edition 0.06 DRAFT, last updated 24 October 1994, of `The
GNU C Library Reference Manual', for Version 1.09 Beta.

   Copyright (C) 1993, 1994 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 translations of the section
entitled "GNU Library General Public License" must be approved for
accuracy by the Foundation.

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.

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.

     #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      "churchy.gnu.ai.mit.edu"

     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,
                                  unsigned short int 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' and `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 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 (unsigned short int 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, &result);

   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 result, success;

           /* If we have reached the mark, return.  */
           success = ioctl (socket, SIOCATMARK, &result);
           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);
           struct buffer *link;
           int success;
           int result;

           /* 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, &result);
           if (success < 0)
             perror ("ioctl");
           if (result)
             {
               /* 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, size_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.

Receiving Datagrams
-------------------

   The `recvfrom' function reads a packet from a datagram socket and
also tells you where it was sent from.  This function is declared in
`sys/socket.h'.

 - Function: int recvfrom (int SOCKET, void *BUFFER, size_t SIZE, int
          FLAGS, struct sockaddr *ADDR, size_t *LENGTH-PTR)
     The `recvfrom' function reads one packet from the socket SOCKET
     into the buffer BUFFER.  The SIZE argument specifies the maximum
     number of bytes to be read.

     If the packet is longer than SIZE bytes, then you get the first
     SIZE bytes of the packet, and the rest of the packet is lost.
     There's no way to read the rest of the packet.  Thus, when you use
     a packet protocol, you must always know how long a packet to
     expect.

     The ADDR and LENGTH-PTR arguments are used to return the address
     where the packet came from.  See Socket Addresses.  For a
     socket in the file domain, the address information won't be
     meaningful, since you can't read the address of such a socket
     (see File Namespace.).  You can specify a null pointer as the
     ADDR argument if you are not interested in this information.

     The FLAGS are interpreted the same way as for `recv' (see Socket Data Options.).
     The return value and error conditions are also
     the same as for `recv'.

   You can use plain `recv' (see Receiving Data.) instead of
`recvfrom' if you know don't need to find out who sent the packet
(either because you know where it should come from or because you treat
all possible senders alike).  Even `read' can be used if you don't want
to specify FLAGS (see I/O Primitives.).

Datagram Socket Example
-----------------------

   Here is a set of example programs that send messages over a datagram
stream in the file namespace.  Both the client and server programs use
the `make_named_socket' function that was presented in File Namespace,
to create and name their sockets.

   First, here is the server program.  It sits in a loop waiting for
messages to arrive, bouncing each message back to the sender.
Obviously, this isn't a particularly useful program, but it does show
the general ideas involved.

     #include <stdio.h>
     #include <errno.h>
     #include <stdlib.h>
     #include <sys/socket.h>
     #include <sys/un.h>

     #define SERVER  "/tmp/serversocket"
     #define MAXMSG  512

     int
     main (void)
     {
       int sock;
       char message[MAXMSG];
       struct sockaddr_un name;
       size_t size;
       int nbytes;

       /* Make the socket, then loop endlessly. */

       sock = make_named_socket (SERVER);
       while (1)
         {
           /* Wait for a datagram. */
           size = sizeof (name);
           nbytes = recvfrom (sock, message, MAXMSG, 0,
                              (struct sockaddr *) & name, &size);
           if (nbytes < 0)
             {
               perror ("recfrom (server)");
               exit (EXIT_FAILURE);
             }

           /* Give a diagnostic message. */
           fprintf (stderr, "Server: got message: %s\n", message);

           /* Bounce the message back to the sender. */
           nbytes = sendto (sock, message, nbytes, 0,
                            (struct sockaddr *) & name, size);
           if (nbytes < 0)
             {
               perror ("sendto (server)");
               exit (EXIT_FAILURE);
             }
         }
     }

Example of Reading Datagrams
----------------------------

   Here is the client program corresponding to the server above.

   It sends a datagram to the server and then waits for a reply.  Notice
that the socket for the client (as well as for the server) in this
example has to be given a name.  This is so that the server can direct
a message back to the client.  Since the socket has no associated
connection state, the only way the server can do this is by referencing
the name of the client.

     #include <stdio.h>
     #include <errno.h>
     #include <unistd.h>
     #include <stdlib.h>
     #include <sys/socket.h>
     #include <sys/un.h>

     #define SERVER  "/tmp/serversocket"
     #define CLIENT  "/tmp/mysocket"
     #define MAXMSG  512
     #define MESSAGE "Yow!!! Are we having fun yet?!?"

     int
     main (void)
     {
       extern int make_named_socket (const char *name);
       int sock;
       char message[MAXMSG];
       struct sockaddr_un name;
       size_t size;
       int nbytes;

       /* Make the socket. */
       sock = make_named_socket (CLIENT);

       /* Initialize the server socket address. */
       name.sun_family = AF_UNIX;
       strcpy (name.sun_path, SERVER);
       size = strlen (name.sun_path) + sizeof (name.sun_family);

       /* Send the datagram. */
       nbytes = sendto (sock, MESSAGE, strlen (MESSAGE) + 1, 0,
                        (struct sockaddr *) & name, size);
       if (nbytes < 0)
         {
           perror ("sendto (client)");
           exit (EXIT_FAILURE);
         }

       /* Wait for a reply. */
       nbytes = recvfrom (sock, message, MAXMSG, 0, NULL, 0);
       if (nbytes < 0)
         {
           perror ("recfrom (client)");
           exit (EXIT_FAILURE);
         }

       /* Print a diagnostic message. */
       fprintf (stderr, "Client: got message: %s\n", message);

       /* Clean up. */
       remove (CLIENT);
       close (sock);
     }

   Keep in mind that datagram socket communications are unreliable.  In
this example, the client program waits indefinitely if the message
never reaches the server or if the server's response never comes back.
It's up to the user running the program to kill it and restart it, if
desired.  A more automatic solution could be to use `select' (see
Waiting for I/O.) to establish a timeout period for the reply, and in
case of timeout either resend the message or shut down the socket and
exit.

The `inetd' Daemon
==================

   We've explained above how to write a server program that does its own
listening.  Such a server must already be running in order for anyone
to connect to it.

   Another way to provide service for an Internet port is to let the
daemon program `inetd' do the listening.  `inetd' is a program that
runs all the time and waits (using `select') for messages on a
specified set of ports.  When it receives a message, it accepts the
connection (if the socket style calls for connections) and then forks a
child process to run the corresponding server program.  You specify the
ports and their programs in the file `/etc/inetd.conf'.

`inetd' Servers
---------------

   Writing a server program to be run by `inetd' is very simple.  Each
time someone requests a connection to the appropriate port, a new server
process starts.  The connection already exists at this time; the socket
is available as the standard input descriptor and as the standard
output descriptor (descriptors 0 and 1) in the server process.  So the
server program can begin reading and writing data right away.  Often
the program needs only the ordinary I/O facilities; in fact, a
general-purpose filter program that knows nothing about sockets can
work as a byte stream server run by `inetd'.

   You can also use `inetd' for servers that use connectionless
communication styles.  For these servers, `inetd' does not try to accept
a connection, since no connection is possible.  It just starts the
server program, which can read the incoming datagram packet from
descriptor 0.  The server program can handle one request and then exit,
or you can choose to write it to keep reading more requests until no
more arrive, and then exit.  You must specify which of these two
techniques the server uses, when you configure `inetd'.

Configuring `inetd'
-------------------

   The file `/etc/inetd.conf' tells `inetd' which ports to listen to
and what server programs to run for them.  Normally each entry in the
file is one line, but you can split it onto multiple lines provided all
but the first line of the entry start with whitespace.  Lines that
start with `#' are comments.

   Here are two standard entries in `/etc/inetd.conf':

     ftp	stream	tcp	nowait	root	/libexec/ftpd	ftpd
     talk	dgram	udp	wait	root	/libexec/talkd	talkd

   An entry has this format:

     SERVICE STYLE PROTOCOL WAIT USERNAME PROGRAM ARGUMENTS

   The SERVICE field says which service this program provides.  It
should be the name of a service defined in `/etc/services'.  `inetd'
uses SERVICE to decide which port to listen on for this entry.

   The fields STYLE and PROTOCOL specify the communication style and
the protocol to use for the listening socket.  The style should be the
name of a communication style, converted to lower case and with `SOCK_'
deleted--for example, `stream' or `dgram'.  PROTOCOL should be one of
the protocols listed in `/etc/protocols'.  The typical protocol names
are `tcp' for byte stream connections and `udp' for unreliable
datagrams.

   The WAIT field should be either `wait' or `nowait'.  Use `wait' if
STYLE is a connectionless style and the server, once started, handles
multiple requests, as many as come in.  Use `nowait' if `inetd' should
start a new process for each message or request that comes in.  If
STYLE uses connections, then WAIT *must* be `nowait'.

   USER is the user name that the server should run as.  `inetd' runs
as root, so it can set the user ID of its children arbitrarily.  It's
best to avoid using `root' for USER if you can; but some servers, such
as Telnet and FTP, read a username and password themselves.  These
servers need to be root initially so they can log in as commanded by
the data coming over the network.

   PROGRAM together with ARGUMENTS specifies the command to run to
start the server.  PROGRAM should be an absolute file name specifying
the executable file to run.  ARGUMENTS consists of any number of
whitespace-separated words, which become the command-line arguments of
PROGRAM.  The first word in ARGUMENTS is argument zero, which should by
convention be the program name itself (sans directories).

   If you edit `/etc/inetd.conf', you can tell `inetd' to reread the
file and obey its new contents by sending the `inetd' process the
`SIGHUP' signal.  You'll have to use `ps' to determine the process ID
of the `inetd' process, as it is not fixed.

Socket Options
==============

   This section describes how to read or set various options that modify
the behavior of sockets and their underlying communications protocols.

   When you are manipulating a socket option, you must specify which
"level" the option pertains to.  This describes whether the option
applies to the socket interface, or to a lower-level communications
protocol interface.

Socket Option Functions
-----------------------

   Here are the functions for examining and modifying socket options.
They are declared in `sys/socket.h'.

 - Function: int getsockopt (int SOCKET, int LEVEL, int OPTNAME, void
          *OPTVAL, size_t *OPTLEN-PTR)
     The `getsockopt' function gets information about the value of
     option OPTNAME at level LEVEL for socket SOCKET.

     The option value is stored in a buffer that OPTVAL points to.
     Before the call, you should supply in `*OPTLEN-PTR' the size of
     this buffer; on return, it contains the number of bytes of
     information actually stored in the buffer.

     Most options interpret the OPTVAL buffer as a single `int' value.

     The actual return value of `getsockopt' is `0' on success and `-1'
     on failure.  The following `errno' error conditions are defined:

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

    `ENOTSOCK'
          The descriptor SOCKET is not a socket.

    `ENOPROTOOPT'
          The OPTNAME doesn't make sense for the given LEVEL.

 - Function: int setsockopt (int SOCKET, int LEVEL, int OPTNAME, void
          *OPTVAL, size_t OPTLEN)
     This function is used to set the socket option OPTNAME at level
     LEVEL for socket SOCKET.  The value of the option is passed in the
     buffer OPTVAL, which has size OPTLEN.

     The return value and error codes for `setsockopt' are the same as
     for `getsockopt'.

Socket-Level Options
--------------------

 - Constant: int SOL_SOCKET
     Use this constant as the LEVEL argument to `getsockopt' or
     `setsockopt' to manipulate the socket-level options described in
     this section.

   Here is a table of socket-level option names; all are defined in the
header file `sys/socket.h'.

`SO_DEBUG'
     This option toggles recording of debugging information in the
     underlying protocol modules.  The value has type `int'; a nonzero
     value means "yes".

`SO_REUSEADDR'
     This option controls whether `bind' (see Setting Address.)
     should permit reuse of local addresses for this socket.  If you
     enable this option, you can actually have two sockets with the
     same Internet port number; but the system won't allow you to use
     the two identically-named sockets in a way that would confuse the
     Internet.  The reason for this option is that some higher-level
     Internet protocols, including FTP, require you to keep reusing the
     same socket number.

     The value has type `int'; a nonzero value means "yes".

`SO_KEEPALIVE'
     This option controls whether the underlying protocol should
     periodically transmit messages on a connected socket.  If the peer
     fails to respond to these messages, the connection is considered
     broken.  The value has type `int'; a nonzero value means "yes".

`SO_DONTROUTE'
     This option controls whether outgoing messages bypass the normal
     message routing facilities.  If set, messages are sent directly to
     the network interface instead.  The value has type `int'; a nonzero
     value means "yes".

`SO_LINGER'
     This option specifies what should happen when the socket of a type
     that promises reliable delivery still has untransmitted messages
     when it is closed; see Closing a Socket.  The value has
     type `struct linger'.

      - Data Type: struct linger
          This structure type has the following members:

         `int l_onoff'
               This field is interpreted as a boolean.  If nonzero,
               `close' blocks until the data is transmitted or the
               timeout period has expired.

         `int l_linger'
               This specifies the timeout period, in seconds.

`SO_BROADCAST'
     This option controls whether datagrams may be broadcast from the
     socket.  The value has type `int'; a nonzero value means "yes".

`SO_OOBINLINE'
     If this option is set, out-of-band data received on the socket is
     placed in the normal input queue.  This permits it to be read using
     `read' or `recv' without specifying the `MSG_OOB' flag.  See
     Out-of-Band Data.  The value has type `int'; a nonzero value
     means "yes".

`SO_SNDBUF'
     This option gets or sets the size of the output buffer.  The value
     is a `size_t', which is the size in bytes.

`SO_RCVBUF'
     This option gets or sets the size of the input buffer.  The value
     is a `size_t', which is the size in bytes.

`SO_STYLE'
`SO_TYPE'
     This option can be used with `getsockopt' only.  It is used to get
     the socket's communication style.  `SO_TYPE' is the historical
     name, and `SO_STYLE' is the preferred name in GNU.  The value has
     type `int' and its value designates a communication style; see
     Communication Styles.

`SO_ERROR'
     This option can be used with `getsockopt' only.  It is used to
     reset the error status of the socket.  The value is an `int',
     which represents the previous error status.

Networks Database
=================

   Many systems come with a database that records a list of networks
known to the system developer.  This is usually kept either in the file
`/etc/networks' or in an equivalent from a name server.  This data base
is useful for routing programs such as `route', but it is not useful
for programs that simply communicate over the network.  We provide
functions to access this data base, which are declared in `netdb.h'.

 - Data Type: struct netent
     This data type is used to represent information about entries in
     the networks database.  It has the following members:

    `char *n_name'
          This is the "official" name of the network.

    `char **n_aliases'
          These are alternative names for the network, represented as a
          vector of strings.  A null pointer terminates the array.

    `int n_addrtype'
          This is the type of the network number; this is always equal
          to `AF_INET' for Internet networks.

    `unsigned long int n_net'
          This is the network number.  Network numbers are returned in
          host byte order; see Byte Order.

   Use the `getnetbyname' or `getnetbyaddr' functions to search the
networks database for information about a specific network.  The
information is returned in a statically-allocated structure; you must
copy the information if you need to save it.

 - Function: struct netent * getnetbyname (const char *NAME)
     The `getnetbyname' function returns information about the network
     named NAME.  It returns a null pointer if there is no such network.

 - Function: struct netent * getnetbyaddr (long NET, int TYPE)
     The `getnetbyaddr' function returns information about the network
     of type TYPE with number NET.  You should specify a value of
     `AF_INET' for the TYPE argument for Internet networks.

     `getnetbyaddr' returns a null pointer if there is no such network.

   You can also scan the networks database using `setnetent',
`getnetent', and `endnetent'.  Be careful in using these functions,
because they are not reentrant.

 - Function: void setnetent (int STAYOPEN)
     This function opens and rewinds the networks database.

     If the STAYOPEN argument is nonzero, this sets a flag so that
     subsequent calls to `getnetbyname' or `getnetbyaddr' 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 netent * getnetent (void)
     This function returns the next entry in the networks database.  It
     returns a null pointer if there are no more entries.

 - Function: void endnetent (void)
     This function closes the networks database.

Low-Level Terminal Interface
****************************

   This chapter describes functions that are specific to terminal
devices.  You can use these functions to do things like turn off input
echoing; set serial line characteristics such as line speed and flow
control; and change which characters are used for end-of-file,
command-line editing, sending signals, and similar control functions.

   Most of the functions in this chapter operate on file descriptors.
See Low-Level I/O, for more information about what a file
descriptor is and how to open a file descriptor for a terminal device.

Identifying Terminals
=====================

   The functions described in this chapter only work on files that
correspond to terminal devices.  You can find out whether a file
descriptor is associated with a terminal by using the `isatty' function.

   Prototypes for both `isatty' and `ttyname' are declared in the
header file `unistd.h'.

 - Function: int isatty (int FILEDES)
     This function returns `1' if FILEDES is a file descriptor
     associated with an open terminal device, and `0' otherwise.

   If a file descriptor is associated with a terminal, you can get its
associated file name using the `ttyname' function.  See also the
`ctermid' function, described in Identifying the Terminal.

 - Function: char * ttyname (int FILEDES)
     If the file descriptor FILEDES is associated with a terminal
     device, the `ttyname' function returns a pointer to a
     statically-allocated, null-terminated string containing the file
     name of the terminal file.  The value is a null pointer if the
     file descriptor isn't associated with a terminal, or the file name
     cannot be determined.

I/O Queues
==========

   Many of the remaining functions in this section refer to the input
and output queues of a terminal device.  These queues implement a form
of buffering *within the kernel* independent of the buffering
implemented by I/O streams (see I/O on Streams.).

   The "terminal input queue" is also sometimes referred to as its
"typeahead buffer".  It holds the characters that have been received
from the terminal but not yet read by any process.

   The size of the terminal's input queue is described by the
`_POSIX_MAX_INPUT' and `MAX_INPUT' parameters; see Limits for Files.
You are guaranteed a queue size of at least `MAX_INPUT', but
the queue might be larger, and might even dynamically change size.  If
input flow control is enabled by setting the `IXOFF' input mode bit
(see Input Modes.), the terminal driver transmits STOP and START
characters to the terminal when necessary to prevent the queue from
overflowing.  Otherwise, input may be lost if it comes in too fast from
the terminal.  In canonical mode, all input stays in the queue until a
newline character is received, so the terminal input queue can fill up
when you type a very long line.  See Canonical or Not.

   The "terminal output queue" is like the input queue, but for output;
it contains characters that have been written by processes, but not yet
transmitted to the terminal.  If output flow control is enabled by
setting the `IXON' input mode bit (see Input Modes.), the terminal
driver obeys STOP and STOP characters sent by the terminal to stop and
restart transmission of output.

   "Clearing" the terminal input queue means discarding any characters
that have been received but not yet read.  Similarly, clearing the
terminal output queue means discarding any characters that have been
written but not yet transmitted.

Two Styles of Input: Canonical or Not
=====================================

   POSIX systems support two basic modes of input: canonical and
noncanonical.

   In "canonical input processing" mode, terminal input is processed in
lines terminated by newline (`'\n''), EOF, or EOL characters.  No input
can be read until an entire line has been typed by the user, and the
`read' function (see I/O Primitives.) returns at most a single line
of input, no matter how many bytes are requested.

   In canonical input mode, the operating system provides input editing
facilities: some characters are interpreted specially to perform editing
operations within the current line of text, such as ERASE and KILL.
See Editing Characters.

   The constants `_POSIX_MAX_CANON' and `MAX_CANON' parameterize the
maximum number of bytes which may appear in a single line of canonical
input.  See Limits for Files.  You are guaranteed a maximum line
length of at least `MAX_CANON' bytes, but the maximum might be larger,
and might even dynamically change size.

   In "noncanonical input processing" mode, characters are not grouped
into lines, and ERASE and KILL processing is not performed.  The
granularity with which bytes are read in noncanonical input mode is
controlled by the MIN and TIME settings.  See Noncanonical Input.

   Most programs use canonical input mode, because this gives the user a
way to edit input line by line.  The usual reason to use noncanonical
mode is when the program accepts single-character commands or provides
its own editing facilities.

   The choice of canonical or noncanonical input is controlled by the
`ICANON' flag in the `c_lflag' member of `struct termios'.  See Local Modes.

Terminal Modes
==============

   This section describes the various terminal attributes that control
how input and output are done.  The functions, data structures, and
symbolic constants are all declared in the header file `termios.h'.

Terminal Mode Data Types
------------------------

   The entire collection of attributes of a terminal is stored in a
structure of type `struct termios'.  This structure is used with the
functions `tcgetattr' and `tcsetattr' to read and set the attributes.

 - Data Type: struct termios
     Structure that records all the I/O attributes of a terminal.  The
     structure includes at least the following members:

    `tcflag_t c_iflag'
          A bit mask specifying flags for input modes; see Input Modes.

    `tcflag_t c_oflag'
          A bit mask specifying flags for output modes; see
          Output Modes.

    `tcflag_t c_cflag'
          A bit mask specifying flags for control modes; see
          Control Modes.

    `tcflag_t c_lflag'
          A bit mask specifying flags for local modes; see Local Modes.

    `cc_t c_cc[NCCS]'
          An array specifying which characters are associated with
          various control functions; see Special Characters.

     The `struct termios' structure also contains members which encode
     input and output transmission speeds, but the representation is
     not specified.  See Line Speed, for how to examine and store
     the speed values.

   The following sections describe the details of the members of the
`struct termios' structure.

 - Data Type: tcflag_t
     This is an unsigned integer type used to represent the various bit
     masks for terminal flags.

 - Data Type: cc_t
     This is an unsigned integer type used to represent characters
     associated with various terminal control functions.

 - Macro: int NCCS
     The value of this macro is the number of elements in the `c_cc'
     array.