This is Info file libc.info, produced by Makeinfo version 1.68 from the
input file libc.texinfo.

INFO-DIR-SECTION GNU libraries
START-INFO-DIR-ENTRY
* Libc: (libc).                 C library.
END-INFO-DIR-ENTRY

   This file documents the GNU C library.

   This is Edition 0.09 DRAFT, last updated 28 Aug 1999, of `The GNU C
Library Reference Manual', for Version 2.2 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.


File: libc.info,  Node: Making Special Files,  Next: Temporary Files,  Prev: File Attributes,  Up: File System Interface

Making Special Files
====================

   The `mknod' function is the primitive for making special files, such
as files that correspond to devices.  The GNU library includes this
function for compatibility with BSD.

   The prototype for `mknod' is declared in `sys/stat.h'.

 - Function: int mknod (const char *FILENAME, int MODE, int DEV)
     The `mknod' function makes a special file with name FILENAME.  The
     MODE specifies the mode of the file, and may include the various
     special file bits, such as `S_IFCHR' (for a character special file)
     or `S_IFBLK' (for a block special file).  *Note Testing File
     Type::.

     The DEV argument specifies which device the special file refers to.
     Its exact interpretation depends on the kind of special file being
     created.

     The return value is `0' on success and `-1' on error.  In addition
     to the usual file name errors (*note File Name Errors::.), the
     following `errno' error conditions are defined for this function:

    `EPERM'
          The calling process is not privileged.  Only the superuser
          can create special files.

    `ENOSPC'
          The directory or file system that would contain the new file
          is full and cannot be extended.

    `EROFS'
          The directory containing the new file can't be modified
          because it's on a read-only file system.

    `EEXIST'
          There is already a file named FILENAME.  If you want to
          replace this file, you must remove the old file explicitly
          first.


File: libc.info,  Node: Temporary Files,  Prev: Making Special Files,  Up: File System Interface

Temporary Files
===============

   If you need to use a temporary file in your program, you can use the
`tmpfile' function to open it.  Or you can use the `tmpnam' (better:
`tmpnam_r') function to provide a name for a temporary file and then
you can open it in the usual way with `fopen'.

   The `tempnam' function is like `tmpnam' but lets you choose what
directory temporary files will go in, and something about what their
file names will look like.  Important for multi-threaded programs is
that `tempnam' is reentrant, while `tmpnam' is not since it returns a
pointer to a static buffer.

   These facilities are declared in the header file `stdio.h'.

 - Function: FILE * tmpfile (void)
     This function creates a temporary binary file for update mode, as
     if by calling `fopen' with mode `"wb+"'.  The file is deleted
     automatically when it is closed or when the program terminates.
     (On some other ISO C systems the file may fail to be deleted if
     the program terminates abnormally).

     This function is reentrant.

     When the sources are compiled with `_FILE_OFFSET_BITS == 64' on a
     32-bit system this function is in fact `tmpfile64', i.e. the LFS
     interface transparently replaces the old interface.

 - Function: FILE * tmpfile64 (void)
     This function is similar to `tmpfile', but the stream it returns a
     pointer to was opened using `tmpfile64'.  Therefore this stream can
     be used for files larger then 2^31 bytes on 32-bit machines.

     Please note that the return type is still `FILE *'.  There is no
     special `FILE' type for the LFS interface.

     If the sources are compiled with `_FILE_OFFSET_BITS == 64' on a 32
     bits machine this function is available under the name `tmpfile'
     and so transparently replaces the old interface.

 - Function: char * tmpnam (char *RESULT)
     This function constructs and returns a valid file name that does
     not refer to any existing file.  If the RESULT argument is a null
     pointer, the return value is a pointer to an internal static
     string, which might be modified by subsequent calls and therefore
     makes this function non-reentrant.  Otherwise, the RESULT argument
     should be a pointer to an array of at least `L_tmpnam' characters,
     and the result is written into that array.

     It is possible for `tmpnam' to fail if you call it too many times
     without removing previously-created files.  This is because the
     limited length of the temporary file names gives room for only a
     finite number of different names.  If `tmpnam' fails it returns a
     null pointer.

     *Warning:* Between the time the pathname is constructed and the
     file is created another process might have created a file with the
     same name using `tmpnam', leading to a possible security hole.  The
     implementation generates names which can hardly be predicted, but
     when opening the file you should use the `O_EXCL' flag.  Using
     `tmpfile' is a safe way to avoid this problem.

 - Function: char * tmpnam_r (char *RESULT)
     This function is nearly identical to the `tmpnam' function, except
     that if RESULT is a null pointer it returns a null pointer.

     This guarantees reentrancy because the non-reentrant situation of
     `tmpnam' cannot happen here.

 - Macro: int L_tmpnam
     The value of this macro is an integer constant expression that
     represents the minimum size of a string large enough to hold a
     file name generated by the `tmpnam' function.

 - Macro: int TMP_MAX
     The macro `TMP_MAX' is a lower bound for how many temporary names
     you can create with `tmpnam'.  You can rely on being able to call
     `tmpnam' at least this many times before it might fail saying you
     have made too many temporary file names.

     With the GNU library, you can create a very large number of
     temporary file names.  If you actually created the files, you
     would probably run out of disk space before you ran out of names.
     Some other systems have a fixed, small limit on the number of
     temporary files.  The limit is never less than `25'.

 - Function: char * tempnam (const char *DIR, const char *PREFIX)
     This function generates a unique temporary file name.  If PREFIX
     is not a null pointer, up to five characters of this string are
     used as a prefix for the file name.  The return value is a string
     newly allocated with `malloc', so you should release its storage
     with `free' when it is no longer needed.

     Because the string is dynamically allocated this function is
     reentrant.

     The directory prefix for the temporary file name is determined by
     testing each of the following in sequence.  The directory must
     exist and be writable.

        * The environment variable `TMPDIR', if it is defined.  For
          security reasons this only happens if the program is not SUID
          or SGID enabled.

        * The DIR argument, if it is not a null pointer.

        * The value of the `P_tmpdir' macro.

        * The directory `/tmp'.

     This function is defined for SVID compatibility.

 - SVID Macro: char * P_tmpdir
     This macro is the name of the default directory for temporary
     files.

   Older Unix systems did not have the functions just described.
Instead they used `mktemp' and `mkstemp'.  Both of these functions work
by modifying a file name template string you pass.  The last six
characters of this string must be `XXXXXX'.  These six `X's are
replaced with six characters which make the whole string a unique file
name.  Usually the template string is something like
`/tmp/PREFIXXXXXXX', and each program uses a unique PREFIX.

   *Note:* Because `mktemp' and `mkstemp' modify the template string,
you *must not* pass string constants to them.  String constants are
normally in read-only storage, so your program would crash when
`mktemp' or `mkstemp' tried to modify the string.

 - Function: char * mktemp (char *TEMPLATE)
     The `mktemp' function generates a unique file name by modifying
     TEMPLATE as described above.  If successful, it returns TEMPLATE
     as modified.  If `mktemp' cannot find a unique file name, it makes
     TEMPLATE an empty string and returns that.  If TEMPLATE does not
     end with `XXXXXX', `mktemp' returns a null pointer.

     *Warning:* Between the time the pathname is constructed and the
     file is created another process might have created a file with the
     same name using `mktemp', leading to a possible security hole.  The
     implementation generates names which can hardly be predicted, but
     when opening the file you should use the `O_EXCL' flag.  Using
     `mkstemp' is a safe way to avoid this problem.

 - Function: int mkstemp (char *TEMPLATE)
     The `mkstemp' function generates a unique file name just as
     `mktemp' does, but it also opens the file for you with `open'
     (*note Opening and Closing Files::.).  If successful, it modifies
     TEMPLATE in place and returns a file descriptor for that file open
     for reading and writing.  If `mkstemp' cannot create a
     uniquely-named file, it returns `-1'.  If TEMPLATE does not end
     with `XXXXXX', `mkstemp' returns `-1' and does not modify TEMPLATE.

     The file is opened using mode `0600'.  If the file is meant to be
     used by other users this mode must be changed explicitly.

   Unlike `mktemp', `mkstemp' is actually guaranteed to create a unique
file that cannot possibly clash with any other program trying to create
a temporary file.  This is because it works by calling `open' with the
`O_EXCL' flag, which says you want to create a new file and get an
error if the file already exists.

 - Function: char * mkdtemp (char *TEMPLATE)
     The `mkdtemp' function creates a directory with a unique name.  If
     it succeeds, it overwrites TEMPLATE with the name of the
     directory, and returns TEMPLATE.  As with `mktemp' and `mkstemp',
     TEMPLATE should be a string ending with `XXXXXX'.

     If `mkdtemp' cannot create an uniquely named directory, it returns
     `NULL' and sets ERRNO appropriately.  If TEMPLATE does not end
     with `XXXXXX', `mkdtemp' returns `NULL' and does not modify
     TEMPLATE.  ERRNO will be set to `EINVAL' in this case.

     The directory is created using mode `0700'.

   The directory created by `mkdtemp' cannot clash with temporary files
or directories created by other users.  This is because directory
creation always works like `open' with `O_EXCL'.  *Note Creating
Directories::.

   The `mkdtemp' function comes from OpenBSD.


File: libc.info,  Node: Pipes and FIFOs,  Next: Sockets,  Prev: File System Interface,  Up: Top

Pipes and FIFOs
***************

   A "pipe" is a mechanism for interprocess communication; data written
to the pipe by one process can be read by another process.  The data is
handled in a first-in, first-out (FIFO) order.  The pipe has no name; it
is created for one use and both ends must be inherited from the single
process which created the pipe.

   A "FIFO special file" is similar to a pipe, but instead of being an
anonymous, temporary connection, a FIFO has a name or names like any
other file.  Processes open the FIFO by name in order to communicate
through it.

   A pipe or FIFO has to be open at both ends simultaneously.  If you
read from a pipe or FIFO file that doesn't have any processes writing
to it (perhaps because they have all closed the file, or exited), the
read returns end-of-file.  Writing to a pipe or FIFO that doesn't have a
reading process is treated as an error condition; it generates a
`SIGPIPE' signal, and fails with error code `EPIPE' if the signal is
handled or blocked.

   Neither pipes nor FIFO special files allow file positioning.  Both
reading and writing operations happen sequentially; reading from the
beginning of the file and writing at the end.

* Menu:

* Creating a Pipe::             Making a pipe with the `pipe' function.
* Pipe to a Subprocess::        Using a pipe to communicate with a
				 child process.
* FIFO Special Files::          Making a FIFO special file.
* Pipe Atomicity::		When pipe (or FIFO) I/O is atomic.


File: libc.info,  Node: Creating a Pipe,  Next: Pipe to a Subprocess,  Up: Pipes and FIFOs

Creating a Pipe
===============

   The primitive for creating a pipe is the `pipe' function.  This
creates both the reading and writing ends of the pipe.  It is not very
useful for a single process to use a pipe to talk to itself.  In typical
use, a process creates a pipe just before it forks one or more child
processes (*note Creating a Process::.).  The pipe is then used for
communication either between the parent or child processes, or between
two sibling processes.

   The `pipe' function is declared in the header file `unistd.h'.

 - Function: int pipe (int FILEDES[2])
     The `pipe' function creates a pipe and puts the file descriptors
     for the reading and writing ends of the pipe (respectively) into
     `FILEDES[0]' and `FILEDES[1]'.

     An easy way to remember that the input end comes first is that file
     descriptor `0' is standard input, and file descriptor `1' is
     standard output.

     If successful, `pipe' returns a value of `0'.  On failure, `-1' is
     returned.  The following `errno' error conditions are defined for
     this function:

    `EMFILE'
          The process has too many files open.

    `ENFILE'
          There are too many open files in the entire system.  *Note
          Error Codes::, for more information about `ENFILE'.  This
          error never occurs in the GNU system.

   Here is an example of a simple program that creates a pipe.  This
program uses the `fork' function (*note Creating a Process::.) to create
a child process.  The parent process writes data to the pipe, which is
read by the child process.

     #include <sys/types.h>
     #include <unistd.h>
     #include <stdio.h>
     #include <stdlib.h>
     
     /* Read characters from the pipe and echo them to `stdout'. */
     
     void
     read_from_pipe (int file)
     {
       FILE *stream;
       int c;
       stream = fdopen (file, "r");
       while ((c = fgetc (stream)) != EOF)
         putchar (c);
       fclose (stream);
     }
     
     /* Write some random text to the pipe. */
     
     void
     write_to_pipe (int file)
     {
       FILE *stream;
       stream = fdopen (file, "w");
       fprintf (stream, "hello, world!\n");
       fprintf (stream, "goodbye, world!\n");
       fclose (stream);
     }
     
     int
     main (void)
     {
       pid_t pid;
       int mypipe[2];
     /* Create the pipe. */
       if (pipe (mypipe))
         {
           fprintf (stderr, "Pipe failed.\n");
           return EXIT_FAILURE;
         }
     
       /* Create the child process. */
       pid = fork ();
       if (pid == (pid_t) 0)
         {
           /* This is the child process.
              Close other end first. */
           close (mypipe[1]);
           read_from_pipe (mypipe[0]);
           return EXIT_SUCCESS;
         }
       else if (pid < (pid_t) 0)
         {
           /* The fork failed. */
           fprintf (stderr, "Fork failed.\n");
           return EXIT_FAILURE;
         }
       else
         {
           /* This is the parent process.
              Close other end first. */
           close (mypipe[0]);
           write_to_pipe (mypipe[1]);
           return EXIT_SUCCESS;
         }
     }


File: libc.info,  Node: Pipe to a Subprocess,  Next: FIFO Special Files,  Prev: Creating a Pipe,  Up: Pipes and FIFOs

Pipe to a Subprocess
====================

   A common use of pipes is to send data to or receive data from a
program being run as a subprocess.  One way of doing this is by using a
combination of `pipe' (to create the pipe), `fork' (to create the
subprocess), `dup2' (to force the subprocess to use the pipe as its
standard input or output channel), and `exec' (to execute the new
program).  Or, you can use `popen' and `pclose'.

   The advantage of using `popen' and `pclose' is that the interface is
much simpler and easier to use.  But it doesn't offer as much
flexibility as using the low-level functions directly.

 - Function: FILE * popen (const char *COMMAND, const char *MODE)
     The `popen' function is closely related to the `system' function;
     see *Note Running a Command::.  It executes the shell command
     COMMAND as a subprocess.  However, instead of waiting for the
     command to complete, it creates a pipe to the subprocess and
     returns a stream that corresponds to that pipe.

     If you specify a MODE argument of `"r"', you can read from the
     stream to retrieve data from the standard output channel of the
     subprocess.  The subprocess inherits its standard input channel
     from the parent process.

     Similarly, if you specify a MODE argument of `"w"', you can write
     to the stream to send data to the standard input channel of the
     subprocess.  The subprocess inherits its standard output channel
     from the parent process.

     In the event of an error `popen' returns a null pointer.  This
     might happen if the pipe or stream cannot be created, if the
     subprocess cannot be forked, or if the program cannot be executed.

 - Function: int pclose (FILE *STREAM)
     The `pclose' function is used to close a stream created by `popen'.
     It waits for the child process to terminate and returns its status
     value, as for the `system' function.

   Here is an example showing how to use `popen' and `pclose' to filter
output through another program, in this case the paging program `more'.

     #include <stdio.h>
     #include <stdlib.h>
     
     void
     write_data (FILE * stream)
     {
       int i;
       for (i = 0; i < 100; i++)
         fprintf (stream, "%d\n", i);
       if (ferror (stream))
         {
           fprintf (stderr, "Output to stream failed.\n");
           exit (EXIT_FAILURE);
         }
     }
     int
     main (void)
     {
       FILE *output;
     
       output = popen ("more", "w");
       if (!output)
         {
           fprintf (stderr, "Could not run more.\n");
           return EXIT_FAILURE;
         }
       write_data (output);
       pclose (output);
       return EXIT_SUCCESS;
     }


File: libc.info,  Node: FIFO Special Files,  Next: Pipe Atomicity,  Prev: Pipe to a Subprocess,  Up: Pipes and FIFOs

FIFO Special Files
==================

   A FIFO special file is similar to a pipe, except that it is created
in a different way.  Instead of being an anonymous communications
channel, a FIFO special file is entered into the file system by calling
`mkfifo'.

   Once you have created a FIFO special file in this way, any process
can open it for reading or writing, in the same way as an ordinary file.
However, it has to be open at both ends simultaneously before you can
proceed to do any input or output operations on it.  Opening a FIFO for
reading normally blocks until some other process opens the same FIFO for
writing, and vice versa.

   The `mkfifo' function is declared in the header file `sys/stat.h'.

 - Function: int mkfifo (const char *FILENAME, mode_t MODE)
     The `mkfifo' function makes a FIFO special file with name
     FILENAME.  The MODE argument is used to set the file's
     permissions; see *Note Setting Permissions::.

     The normal, successful return value from `mkfifo' is `0'.  In the
     case of an error, `-1' is returned.  In addition to the usual file
     name errors (*note File Name Errors::.), the following `errno'
     error conditions are defined for this function:

    `EEXIST'
          The named file already exists.

    `ENOSPC'
          The directory or file system cannot be extended.

    `EROFS'
          The directory that would contain the file resides on a
          read-only file system.


File: libc.info,  Node: Pipe Atomicity,  Prev: FIFO Special Files,  Up: Pipes and FIFOs

Atomicity of Pipe I/O
=====================

   Reading or writing pipe data is "atomic" if the size of data written
is not greater than `PIPE_BUF'.  This means that the data transfer
seems to be an instantaneous unit, in that nothing else in the system
can observe a state in which it is partially complete.  Atomic I/O may
not begin right away (it may need to wait for buffer space or for data),
but once it does begin it finishes immediately.

   Reading or writing a larger amount of data may not be atomic; for
example, output data from other processes sharing the descriptor may be
interspersed.  Also, once `PIPE_BUF' characters have been written,
further writes will block until some characters are read.

   *Note Limits for Files::, for information about the `PIPE_BUF'
parameter.


File: libc.info,  Node: Sockets,  Next: Low-Level Terminal Interface,  Prev: Pipes and FIFOs,  Up: Top

Sockets
*******

   This chapter describes the GNU facilities for interprocess
communication using sockets.

   A "socket" is a generalized interprocess communication channel.
Like a pipe, a socket is represented as a file descriptor.  Unlike pipes
sockets support communication between unrelated processes, and even
between processes running on different machines that communicate over a
network.  Sockets are the primary means of communicating with other
machines; `telnet', `rlogin', `ftp', `talk' and the other familiar
network programs use sockets.

   Not all operating systems support sockets.  In the GNU library, the
header file `sys/socket.h' exists regardless of the operating system,
and the socket functions always exist, but if the system does not
really support sockets these functions always fail.

   *Incomplete:* We do not currently document the facilities for
broadcast messages or for configuring Internet interfaces.  The
reentrant functions and some newer functions that are related to IPv6
aren't documented either so far.

* Menu:

* Socket Concepts::	Basic concepts you need to know about.
* Communication Styles::Stream communication, datagrams and other styles.
* Socket Addresses::	How socket names ("addresses") work.
* Interface Naming::	Identifying specific network interfaces.
* Local Namespace::	Details about the local namespace.
* Internet Namespace::	Details about the Internet namespace.
* Misc Namespaces::	Other namespaces not documented fully here.
* Open/Close Sockets::  Creating sockets and destroying them.
* Connections::		Operations on sockets with connection state.
* Datagrams::		Operations on datagram sockets.
* Inetd::		Inetd is a daemon that starts servers on request.
			   The most convenient way to write a server
			   is to make it work with Inetd.
* Socket Options::	Miscellaneous low-level socket options.
* Networks Database::   Accessing the database of network names.


File: libc.info,  Node: Socket Concepts,  Next: Communication Styles,  Up: Sockets

Socket Concepts
===============

   When you create a socket, you must specify the style of communication
you want to use and the type of protocol that should implement it.  The
"communication style" of a socket defines the user-level semantics of
sending and receiving data on the socket.  Choosing a communication
style specifies the answers to questions such as these:

   * *What are the units of data transmission?*  Some communication
     styles regard the data as a sequence of bytes with no larger
     structure; others group the bytes into records (which are known in
     this context as "packets").

   * *Can data be lost during normal operation?*  Some communication
     styles guarantee that all the data sent arrives in the order it was
     sent (barring system or network crashes); other styles occasionally
     lose data as a normal part of operation, and may sometimes deliver
     packets more than once or in the wrong order.

     Designing a program to use unreliable communication styles usually
     involves taking precautions to detect lost or misordered packets
     and to retransmit data as needed.

   * *Is communication entirely with one partner?*  Some communication
     styles are like a telephone call--you make a "connection" with one
     remote socket and then exchange data freely.  Other styles are
     like mailing letters--you specify a destination address for each
     message you send.

   You must also choose a "namespace" for naming the socket.  A socket
name ("address") is meaningful only in the context of a particular
namespace.  In fact, even the data type to use for a socket name may
depend on the namespace.  Namespaces are also called "domains", but we
avoid that word as it can be confused with other usage of the same
term.  Each namespace has a symbolic name that starts with `PF_'.  A
corresponding symbolic name starting with `AF_' designates the address
format for that namespace.

   Finally you must choose the "protocol" to carry out the
communication.  The protocol determines what low-level mechanism is used
to transmit and receive data.  Each protocol is valid for a particular
namespace and communication style; a namespace is sometimes called a
"protocol family" because of this, which is why the namespace names
start with `PF_'.

   The rules of a protocol apply to the data passing between two
programs, perhaps on different computers; most of these rules are
handled by the operating system and you need not know about them.  What
you do need to know about protocols is this:

   * In order to have communication between two sockets, they must
     specify the *same* protocol.

   * Each protocol is meaningful with particular style/namespace
     combinations and cannot be used with inappropriate combinations.
     For example, the TCP protocol fits only the byte stream style of
     communication and the Internet namespace.

   * For each combination of style and namespace there is a "default
     protocol", which you can request by specifying 0 as the protocol
     number.  And that's what you should normally do--use the default.

   Throughout the following description at various places
variables/parameters to denote sizes are required.  And here the trouble
starts.  In the first implementations the type of these variables was
simply `int'.  On most machines at that time an `int' was 32 bits wide,
which created a *de facto* standard requiring 32-bit variables.  This
is important since references to variables of this type are passed to
the kernel.

   Then the POSIX people came and unified the interface with the words
"all size values are of type `size_t'".  On 64-bit machines `size_t' is
64 bits wide, so pointers to variables were no longer possible.

   The Unix98 specification provides a solution by introducing a type
`socklen_t'.  This type is used in all of the cases that POSIX changed
to use `size_t'.  The only requirement of this type is that it be an
unsigned type of at least 32 bits.  Therefore, implementations which
require that references to 32-bit variables be passed can be as happy
as implementations which use 64-bit values.


File: libc.info,  Node: Communication Styles,  Next: Socket Addresses,  Prev: Socket Concepts,  Up: Sockets

Communication Styles
====================

   The GNU library includes support for several different kinds of
sockets, each with different characteristics.  This section describes
the supported socket types.  The symbolic constants listed here are
defined in `sys/socket.h'.

 - Macro: int SOCK_STREAM
     The `SOCK_STREAM' style is like a pipe (*note Pipes and FIFOs::.).
     It operates over a connection with a particular remote socket and
     transmits data reliably as a stream of bytes.

     Use of this style is covered in detail in *Note Connections::.

 - Macro: int SOCK_DGRAM
     The `SOCK_DGRAM' style is used for sending individually-addressed
     packets unreliably.  It is the diametrical opposite of
     `SOCK_STREAM'.

     Each time you write data to a socket of this kind, that data
     becomes one packet.  Since `SOCK_DGRAM' sockets do not have
     connections, you must specify the recipient address with each
     packet.

     The only guarantee that the system makes about your requests to
     transmit data is that it will try its best to deliver each packet
     you send.  It may succeed with the sixth packet after failing with
     the fourth and fifth packets; the seventh packet may arrive before
     the sixth, and may arrive a second time after the sixth.

     The typical use for `SOCK_DGRAM' is in situations where it is
     acceptable to simply re-send a packet if no response is seen in a
     reasonable amount of time.

     *Note Datagrams::, for detailed information about how to use
     datagram sockets.

 - Macro: int SOCK_RAW
     This style provides access to low-level network protocols and
     interfaces.  Ordinary user programs usually have no need to use
     this style.


File: libc.info,  Node: Socket Addresses,  Next: Interface Naming,  Prev: Communication Styles,  Up: Sockets

Socket Addresses
================

   The name of a socket is normally called an "address".  The functions
and symbols for dealing with socket addresses were named
inconsistently, sometimes using the term "name" and sometimes using
"address".  You can regard these terms as synonymous where sockets are
concerned.

   A socket newly created with the `socket' function has no address.
Other processes can find it for communication only if you give it an
address.  We call this "binding" the address to the socket, and the way
to do it is with the `bind' function.

   You need be concerned with the address of a socket if other processes
are to find it and start communicating with it.  You can specify an
address for other sockets, but this is usually pointless; the first time
you send data from a socket, or use it to initiate a connection, the
system assigns an address automatically if you have not specified one.

   Occasionally a client needs to specify an address because the server
discriminates based on address; for example, the rsh and rlogin
protocols look at the client's socket address and only bypass password
checking if it is less than `IPPORT_RESERVED' (*note Ports::.).

   The details of socket addresses vary depending on what namespace you
are using.  *Note Local Namespace::, or *Note Internet Namespace::, for
specific information.

   Regardless of the namespace, you use the same functions `bind' and
`getsockname' to set and examine a socket's address.  These functions
use a phony data type, `struct sockaddr *', to accept the address.  In
practice, the address lives in a structure of some other data type
appropriate to the address format you are using, but you cast its
address to `struct sockaddr *' when you pass it to `bind'.

* Menu:

* Address Formats::		About `struct sockaddr'.
* Setting Address::		Binding an address to a socket.
* Reading Address::		Reading the address of a socket.


File: libc.info,  Node: Address Formats,  Next: Setting Address,  Up: Socket Addresses

Address Formats
---------------

   The functions `bind' and `getsockname' use the generic data type
`struct sockaddr *' to represent a pointer to a socket address.  You
can't use this data type effectively to interpret an address or
construct one; for that, you must use the proper data type for the
socket's namespace.

   Thus, the usual practice is to construct an address of the proper
namespace-specific type, then cast a pointer to `struct sockaddr *'
when you call `bind' or `getsockname'.

   The one piece of information that you can get from the `struct
sockaddr' data type is the "address format designator".  This tells you
which data type to use to understand the address fully.

   The symbols in this section are defined in the header file
`sys/socket.h'.

 - Data Type: struct sockaddr
     The `struct sockaddr' type itself has the following members:

    `short int sa_family'
          This is the code for the address format of this address.  It
          identifies the format of the data which follows.

    `char sa_data[14]'
          This is the actual socket address data, which is
          format-dependent.  Its length also depends on the format, and
          may well be more than 14.  The length 14 of `sa_data' is
          essentially arbitrary.

   Each address format has a symbolic name which starts with `AF_'.
Each of them corresponds to a `PF_' symbol which designates the
corresponding namespace.  Here is a list of address format names:

`AF_LOCAL'
     This designates the address format that goes with the local
     namespace.  (`PF_LOCAL' is the name of that namespace.)  *Note
     Local Namespace Details::, for information about this address
     format.

`AF_UNIX'
     This is a synonym for `AF_LOCAL'.  Although `AF_LOCAL' is mandated
     by POSIX.1g, `AF_UNIX' is portable to more systems.  `AF_UNIX' was
     the traditional name stemming from BSD, so even most POSIX systems
     support it.  It is also the name of choice in the Unix98
     specification. (The same is true for `PF_UNIX' vs. `PF_LOCAL').

`AF_FILE'
     This is another synonym for `AF_LOCAL', for compatibility.
     (`PF_FILE' is likewise a synonym for `PF_LOCAL'.)

`AF_INET'
     This designates the address format that goes with the Internet
     namespace.  (`PF_INET' is the name of that namespace.)  *Note
     Internet Address Formats::.

`AF_INET6'
     This is similar to `AF_INET', but refers to the IPv6 protocol.
     (`PF_INET6' is the name of the corresponding namespace.)

`AF_UNSPEC'
     This designates no particular address format.  It is used only in
     rare cases, such as to clear out the default destination address
     of a "connected" datagram socket.  *Note Sending Datagrams::.

     The corresponding namespace designator symbol `PF_UNSPEC' exists
     for completeness, but there is no reason to use it in a program.

   `sys/socket.h' defines symbols starting with `AF_' for many
different kinds of networks, most or all of which are not actually
implemented.  We will document those that really work as we receive
information about how to use them.


File: libc.info,  Node: Setting Address,  Next: Reading Address,  Prev: Address Formats,  Up: Socket Addresses

Setting the Address of a Socket
-------------------------------

   Use the `bind' function to assign an address to a socket.  The
prototype for `bind' is in the header file `sys/socket.h'.  For
examples of use, see *Note Local Socket Example::, or see *Note Inet
Example::.

 - Function: int bind (int SOCKET, struct sockaddr *ADDR, socklen_t
          LENGTH)
     The `bind' function assigns an address to the socket SOCKET.  The
     ADDR and LENGTH arguments specify the address; the detailed format
     of the address depends on the namespace.  The first part of the
     address is always the format designator, which specifies a
     namespace, and says that the address is in the format of that
     namespace.

     The return value is `0' on success and `-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.

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

    `EADDRINUSE'
          Some other socket is already using the specified address.

    `EINVAL'
          The socket SOCKET already has an address.

    `EACCES'
          You do not have permission to access the requested address.
          (In the Internet domain, only the super-user is allowed to
          specify a port number in the range 0 through
          `IPPORT_RESERVED' minus one; see *Note Ports::.)

     Additional conditions may be possible depending on the particular
     namespace of the socket.


File: libc.info,  Node: Reading Address,  Prev: Setting Address,  Up: Socket Addresses

Reading the Address of a Socket
-------------------------------

   Use the function `getsockname' to examine the address of an Internet
socket.  The prototype for this function is in the header file
`sys/socket.h'.

 - Function: int getsockname (int SOCKET, struct sockaddr *ADDR,
          socklen_t *LENGTH-PTR)
     The `getsockname' function returns information about the address
     of the socket SOCKET in the locations specified by the ADDR and
     LENGTH-PTR arguments.  Note that the LENGTH-PTR is a pointer; you
     should initialize it to be the allocation size of ADDR, and on
     return it contains the actual size of the address data.

     The format of the address data depends on the socket namespace.
     The length of the information is usually fixed for a given
     namespace, so normally you can know exactly how much space is
     needed and can provide that much.  The usual practice is to
     allocate a place for the value using the proper data type for the
     socket's namespace, then cast its address to `struct sockaddr *'
     to pass it to `getsockname'.

     The return value is `0' on success and `-1' on error.  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.

    `ENOBUFS'
          There are not enough internal buffers available for the
          operation.

   You can't read the address of a socket in the file namespace.  This
is consistent with the rest of the system; in general, there's no way to
find a file's name from a descriptor for that file.


File: libc.info,  Node: Interface Naming,  Next: Local Namespace,  Prev: Socket Addresses,  Up: Sockets

Interface Naming
================

   Each network interface has a name.  This usually consists of a few
letters that relate to the type of interface, which may be followed by a
number if there is more than one interface of that type.  Examples
might be `lo' (the loopback interface) and `eth0' (the first Ethernet
interface).

   Although such names are convenient for humans, it would be clumsy to
have to use them whenever a program needs to refer to an interface.  In
such situations an interface is referred to by its "index", which is an
arbitrarily-assigned small positive integer.

   The following functions, constants and data types are declared in the
header file `net/if.h'.

 - Constant: size_t IFNAMSIZ
     This constant defines the maximum buffer size needed to hold an
     interface name, including its terminating zero byte.

 - Function: unsigned int if_nametoindex (const char *ifname)
     This function yields the interface index corresponding to a
     particular name.  If no interface exists with the name given, it
     returns 0.

 - Function: char * if_indextoname (unsigned int ifindex, char *ifname)
     This function maps an interface index to its corresponding name.
     The returned name is placed in the buffer pointed to by `ifname',
     which must be at least `IFNAMSIZ' bytes in length.  If the index
     was invalid, the function's return value is a null pointer,
     otherwise it is `ifname'.

 - Data Type: struct if_nameindex
     This data type is used to hold the information about a single
     interface.  It has the following members:

    `unsigned int if_index;'
          This is the interface index.

    `char *if_name'
          This is the null-terminated index name.


 - Function: struct if_nameindex * if_nameindex (void)
     This function returns an array of `if_nameindex' structures, one
     for every interface that is present.  The end of the list is
     indicated by a structure with an interface of 0 and a null name
     pointer.  If an error occurs, this function returns a null pointer.

     The returned structure must be freed with `if_freenameindex' after
     use.

 - Function: void if_freenameindex (struct if_nameindex *ptr)
     This function frees the structure returned by an earlier call to
     `if_nameindex'.


File: libc.info,  Node: Local Namespace,  Next: Internet Namespace,  Prev: Interface Naming,  Up: Sockets

The Local Namespace
===================

   This section describes the details of the local namespace, whose
symbolic name (required when you create a socket) is `PF_LOCAL'.  The
local namespace is also known as "Unix domain sockets".  Another name
is file namespace since socket addresses are normally implemented as
file names.

* Menu:

* Concepts: Local Namespace Concepts. What you need to understand.
* Details: Local Namespace Details.   Address format, symbolic names, etc.
* Example: Local Socket Example.      Example of creating a socket.


File: libc.info,  Node: Local Namespace Concepts,  Next: Local Namespace Details,  Up: Local Namespace

Local Namespace Concepts
------------------------

   In the local namespace socket addresses are file names.  You can
specify any file name you want as the address of the socket, but you
must have write permission on the directory containing it.  In order to
connect to a socket you must have read permission for it.  It's common
to put these files in the `/tmp' directory.

   One peculiarity of the local namespace is that the name is only used
when opening the connection; once open the address is not meaningful and
may not exist.

   Another peculiarity is that you cannot connect to such a socket from
another machine-not even if the other machine shares the file system
which contains the name of the socket.  You can see the socket in a
directory listing, but connecting to it never succeeds.  Some programs
take advantage of this, such as by asking the client to send its own
process ID, and using the process IDs to distinguish between clients.
However, we recommend you not use this method in protocols you design,
as we might someday permit connections from other machines that mount
the same file systems.  Instead, send each new client an identifying
number if you want it to have one.

   After you close a socket in the local namespace, you should delete
the file name from the file system.  Use `unlink' or `remove' to do
this; see *Note Deleting Files::.

   The local namespace supports just one protocol for any communication
style; it is protocol number `0'.


File: libc.info,  Node: Local Namespace Details,  Next: Local Socket Example,  Prev: Local Namespace Concepts,  Up: Local Namespace

Details of Local Namespace
--------------------------

   To create a socket in the local namespace, use the constant
`PF_LOCAL' as the NAMESPACE argument to `socket' or `socketpair'.  This
constant is defined in `sys/socket.h'.

 - Macro: int PF_LOCAL
     This designates the local namespace, in which socket addresses are
     local names, and its associated family of protocols.  `PF_Local'
     is the macro used by Posix.1g.

 - Macro: int PF_UNIX
     This is a synonym for `PF_LOCAL', for compatibility's sake.

 - Macro: int PF_FILE
     This is a synonym for `PF_LOCAL', for compatibility's sake.

   The structure for specifying socket names in the local namespace is
defined in the header file `sys/un.h':

 - Data Type: struct sockaddr_un
     This structure is used to specify local namespace socket
     addresses.  It has the following members:

    `short int sun_family'
          This identifies the address family or format of the socket
          address.  You should store the value `AF_LOCAL' to designate
          the local namespace.  *Note Socket Addresses::.

    `char sun_path[108]'
          This is the file name to use.

          *Incomplete:*  Why is 108 a magic number?  RMS suggests making
          this a zero-length array and tweaking the following example
          to use `alloca' to allocate an appropriate amount of storage
          based on the length of the filename.

   You should compute the LENGTH parameter for a socket address in the
local namespace as the sum of the size of the `sun_family' component
and the string length (*not* the allocation size!) of the file name
string.  This can be done using the macro `SUN_LEN':

 - Macro: int SUN_LEN (*struct sockaddr_un ** PTR)
     The macro computes the length of socket address in the local
     namespace.


File: libc.info,  Node: Local Socket Example,  Prev: Local Namespace Details,  Up: Local Namespace

Example of Local-Namespace Sockets
----------------------------------

   Here is an example showing how to create and name a socket in the
local namespace.

     #include <stddef.h>
     #include <stdio.h>
     #include <errno.h>
     #include <stdlib.h>
     #include <sys/socket.h>
     #include <sys/un.h>
     
     int
     make_named_socket (const char *filename)
     {
       struct sockaddr_un name;
       int sock;
       size_t size;
     
       /* Create the socket. */
       sock = socket (PF_LOCAL, SOCK_DGRAM, 0);
       if (sock < 0)
         {
           perror ("socket");
           exit (EXIT_FAILURE);
         }
     
       /* Bind a name to the socket. */
       name.sun_family = AF_LOCAL;
       strncpy (name.sun_path, filename, sizeof (name.sun_path));
     
       /* The size of the address is
          the offset of the start of the filename,
          plus its length,
          plus one for the terminating null byte.
          Alternatively you can just do:
          size = SUN_LEN (&name);
      */
       size = (offsetof (struct sockaddr_un, sun_path)
               + strlen (name.sun_path) + 1);
     
       if (bind (sock, (struct sockaddr *) &name, size) < 0)
         {
           perror ("bind");
           exit (EXIT_FAILURE);
         }
     
       return sock;
     }


File: libc.info,  Node: Internet Namespace,  Next: Misc Namespaces,  Prev: Local Namespace,  Up: Sockets

The Internet Namespace
======================

   This section describes the details of the protocols and socket naming
conventions used in the Internet namespace.

   Originally the Internet namespace used only IP version 4 (IPv4).
With the growing number of hosts on the Internet, a new protocol with a
larger address space was necessary: IP version 6 (IPv6).  IPv6
introduces 128-bit addresses (IPv4 has 32-bit addresses) and other
features, and will eventually replace IPv4.

   To create a socket in the IPv4 Internet namespace, use the symbolic
name `PF_INET' of this namespace as the NAMESPACE argument to `socket'
or `socketpair'.  For IPv6 addresses you need the macro `PF_INET6'.
These macros are defined in `sys/socket.h'.

 - Macro: int PF_INET
     This designates the IPv4 Internet namespace and associated family
     of protocols.

 - Macro: int PF_INET6
     This designates the IPv6 Internet namespace and associated family
     of protocols.

   A socket address for the Internet namespace includes the following
components:

   * The address of the machine you want to connect to.  Internet
     addresses can be specified in several ways; these are discussed in
     *Note Internet Address Formats::, *Note Host Addresses:: and *Note
     Host Names::.

   * A port number for that machine.  *Note Ports::.

   You must ensure that the address and port number are represented in a
canonical format called "network byte order".  *Note Byte Order::, for
information about this.

* Menu:

* Internet Address Formats::    How socket addresses are specified in the
                                 Internet namespace.
* Host Addresses::	        All about host addresses of Internet host.
* Protocols Database::		Referring to protocols by name.
* Ports::			Internet port numbers.
* Services Database::           Ports may have symbolic names.
* Byte Order::		        Different hosts may use different byte
                                 ordering conventions; you need to
                                 canonicalize host address and port number.
* Inet Example::	        Putting it all together.


File: libc.info,  Node: Internet Address Formats,  Next: Host Addresses,  Up: Internet Namespace

Internet Socket Address Formats
-------------------------------

   In the Internet namespace, for both IPv4 (`AF_INET') and IPv6
(`AF_INET6'), a socket address consists of a host address and a port on
that host.  In addition, the protocol you choose serves effectively as
a part of the address because local port numbers are meaningful only
within a particular protocol.

   The data types for representing socket addresses in the Internet
namespace are defined in the header file `netinet/in.h'.

 - Data Type: struct sockaddr_in
     This is the data type used to represent socket addresses in the
     Internet namespace.  It has the following members:

    `sa_family_t sin_family'
          This identifies the address family or format of the socket
          address.  You should store the value `AF_INET' in this member.
          *Note Socket Addresses::.

    `struct in_addr sin_addr'
          This is the Internet address of the host machine.  *Note Host
          Addresses::, and *Note Host Names::, for how to get a value
          to store here.

    `unsigned short int sin_port'
          This is the port number.  *Note Ports::.

   When you call `bind' or `getsockname', you should specify `sizeof
(struct sockaddr_in)' as the LENGTH parameter if you are using an IPv4
Internet namespace socket address.

 - Data Type: struct sockaddr_in6
     This is the data type used to represent socket addresses in the
     IPv6 namespace.  It has the following members:

    `sa_family_t sin6_family'
          This identifies the address family or format of the socket
          address.  You should store the value of `AF_INET6' in this
          member.  *Note Socket Addresses::.

    `struct in6_addr sin6_addr'
          This is the IPv6 address of the host machine.  *Note Host
          Addresses::, and *Note Host Names::, for how to get a value
          to store here.

    `uint32_t sin6_flowinfo'
          This is a currently unimplemented field.

    `uint16_t sin6_port'
          This is the port number.  *Note Ports::.


