Chapter 143. TCP/IP Library Reference

143.1. getdomainname

GETDOMAINNAME(3)         BSD Library Functions Manual         GETDOMAINNAME(3)

NAME
     getdomainname, setdomainname -- get/set YP domain name of current host

SYNOPSIS
     #include <unistd.h>

     int
     getdomainname(char *name, size_t namelen);

     int
     setdomainname(const char *name, size_t namelen);

DESCRIPTION
     The getdomainname() function returns the YP domain name for the current
     processor, as previously set by setdomainname().  The parameter namelen
     specifies the size of the name array.  If insufficient space is provided,
     the returned name is truncated.  The returned name is always null termi-
     nated.

     setdomainname() sets the domain name of the host machine to be name,
     which has length namelen.  This call is restricted to the superuser and
     is normally used only when the system is bootstrapped.

RETURN VALUES
     If the call succeeds a value of 0 is returned.  If the call fails, a
     value of -1 is returned and an error code is placed in the global vari-
     able errno.

ERRORS
     The following errors may be returned by these calls:

     [EFAULT]           The name or namelen parameter gave an invalid address.

     [EPERM]            The caller tried to set the domain name and was not
                        the superuser.

SEE ALSO
     domainname(1), gethostid(3), gethostname(3), sysctl(3), sysctl(8), yp(8)

BUGS
     Domain names are limited to MAXHOSTNAMELEN (from <sys/param.h>) charac-
     ters, currently 256.  This includes the terminating NUL character.

     If the buffer passed to getdomainname() is too small, other operating
     systems may not guarantee termination with NUL.

HISTORY
     The getdomainname function call appeared in SunOS 3.x.

BSD                               May 6, 1994                              BSD

143.2. gethostname

GETHOSTNAME(3)           BSD Library Functions Manual           GETHOSTNAME(3)

NAME
     gethostname, sethostname -- get/set name of current host

SYNOPSIS
     #include <unistd.h>

     int
     gethostname(char *name, size_t namelen);

     int
     sethostname(const char *name, size_t namelen);

DESCRIPTION
     The gethostname() function returns the standard host name for the current
     processor, as previously set by sethostname().  The parameter namelen
     specifies the size of the name array.  If insufficient space is provided,
     the returned name is truncated.  The returned name is always null termi-
     nated.

     sethostname() sets the name of the host machine to be name, which has
     length namelen.  This call is restricted to the superuser and is normally
     used only when the system is bootstrapped.

RETURN VALUES
     If the call succeeds a value of 0 is returned.  If the call fails, a
     value of -1 is returned and an error code is placed in the global vari-
     able errno.

ERRORS
     The following errors may be returned by these calls:

     [EFAULT]           The name or namelen parameter gave an invalid address.

     [EPERM]            The caller tried to set the hostname and was not the
                        superuser.

SEE ALSO
     hostname(1), getdomainname(3), gethostid(3), sysctl(3), sysctl(8), yp(8)

STANDARDS
     The gethostname() function call conforms to X/Open Portability Guide
     Issue 4, Version 2 (``XPG4.2'').

HISTORY
     The gethostname() function call appeared in 4.2BSD.

BUGS
     Host names are limited to MAXHOSTNAMELEN (from <sys/param.h>) characters,
     currently 256.  This includes the terminating NUL character.

     If the buffer passed to gethostname() is smaller than MAXHOSTNAMELEN,
     other operating systems may not guarantee termination with NUL.

BSD                              June 4, 1993                              BSD

143.3. byteorder

BYTEORDER(3)             BSD Library Functions Manual             BYTEORDER(3)

NAME
     htonl, htons, ntohl, ntohs, htobe32, htobe16, betoh32, betoh16, htole32,
     htole16, letoh32, letoh16, swap32, swap16 -- convert values between dif-
     ferent byte orderings

SYNOPSIS
     #include <sys/types.h>
     #include <machine/endian.h>

     u_int32_t
     htonl(u_int32_t host32);

     u_int16_t
     htons(u_int16_t host16);

     u_int32_t
     ntohl(u_int32_t net32);

     u_int16_t
     ntohs(u_int16_t net16);

     u_int32_t
     htobe32(u_int32_t host32);

     u_int16_t
     htobe16(u_int16_t host16);

     u_int32_t
     betoh32(u_int32_t big32);

     u_int16_t
     betoh16(u_int16_t big16);

     u_int32_t
     htole32(u_int32_t host32);

     u_int16_t
     htole16(u_int16_t host16);

     u_int32_t
     letoh32(u_int32_t little32);

     u_int16_t
     letoh16(u_int16_t little16);

     u_int32_t
     swap32(u_int32_t val32);

     u_int16_t
     swap16(u_int16_t val16);

DESCRIPTION
     These routines convert 16- and 32-bit quantities between different byte
     orderings.  The ``swap'' functions reverse the byte ordering of the given
     quantity, the others converts either from/to the native byte order used
     by the host to/from either little- or big-endian (a.k.a network) order.

     Apart from the swap functions, the names can be described by this form:
     {src-order}to{dst-order}{size}.  Both {src-order} and {dst-order} can
     take the following forms:

           h    Host order.
           n    Network order (big-endian).
           be   Big-endian (most significant byte first).
           le   Little-endian (least significant byte first).

     One of the specified orderings must be `h'.  {size} will take these
     forms:

           l  Long (32-bit, used in conjunction with forms involving `n').
           s  Short (16-bit, used in conjunction with forms involving `n').
           16
              16-bit.
           32
              32-bit.

     The swap functions are of the form: swap{size}.

     Names involving `n' convert quantities between network byte order and
     host byte order.  The last letter (`s' or `l') is a mnemonic for the tra-
     ditional names for such quantities, short and long, respectively.  Today,
     the C concept of short and long integers need not coincide with this tra-
     ditional misunderstanding.  On machines which have a byte order which is
     the same as the network order, routines are defined as null macros.

     The functions involving either ``be'', ``le'', or ``swap'' use the num-
     bers 16 and 32 for specifying the bitwidth of the quantities they operate
     on.  Currently all supported architectures are either big- or little-
     endian so either the ``be'' or ``le'' variants are implemented as null
     macros.

     The routines mentioned above which have either {src-order} or {dst-order}
     set to `n' are most often used in conjunction with Internet addresses and
     ports as returned by gethostbyname(3) and getservent(3).

SEE ALSO
     gethostbyname(3), getservent(3)

HISTORY
     The byteorder functions appeared in 4.2BSD.

BUGS
     On the vax, alpha, i386, and so far mips, bytes are handled backwards
     from most everyone else in the world.  This is not expected to be fixed
     in the near future.

BSD                              June 4, 1993                              BSD

143.4. ethers

ETHERS(3)                BSD Library Functions Manual                ETHERS(3)

NAME
     ether_aton, ether_ntoa, ether_addr, ether_ntohost, ether_hostton,
     ether_line -- get ethers entry

SYNOPSIS
     #include <netinet/if_ether.h>

     char *
     ether_ntoa(struct ether_addr *e);

     struct ether_addr *
     ether_aton(char *s);

     int
     ether_ntohost(char *hostname, struct ether_addr *e);

     int
     ether_hostton(char *hostname, struct ether_addr *e);

     int
     ether_line(char *l, struct ether_addr *e, char *hostname);

DESCRIPTION
     Ethernet addresses are represented by the following structure:

           struct ether_addr {
                   u_int8_t  ether_addr_octet[6];
           };

     The ether_ntoa() function converts this structure into an ASCII string of
     the form ``xx:xx:xx:xx:xx:xx'', consisting of 6 hexadecimal numbers sepa-
     rated by colons.  It returns a pointer to a static buffer that is reused
     for each call.  The ether_aton() converts an ASCII string of the same
     form and to a structure containing the 6 octets of the address.  It
     returns a pointer to a static structure that is reused for each call.

     The ether_ntohost() and ether_hostton() functions interrogate the data-
     base mapping host names to Ethernet addresses, /etc/ethers.  The
     ether_ntohost() function looks up the given Ethernet address and writes
     the associated host name into the character buffer passed.  This buffer
     should be MAXHOSTNAMELEN characters in size.  The ether_hostton() func-
     tion looks up the given host name and writes the associated Ethernet
     address into the structure passed.  Both functions return zero if they
     find the requested host name or address, and -1 if not.

     Each call reads /etc/ethers from the beginning; if a `+' appears alone on
     a line in the file, then ether_hostton() will consult the ethers.byname
     YP map, and ether_ntohost() will consult the ethers.byaddr YP map.

     The ether_line() function parses a line from the /etc/ethers file and
     fills in the passed struct ether_addr and character buffer with the Eth-
     ernet address and host name on the line.  It returns zero if the line was
     successfully parsed and -1 if not.  The character buffer should be
     MAXHOSTNAMELEN characters in size.

FILES
     /etc/ethers

SEE ALSO
     ethers(5)

HISTORY
     The ether_ntoa(), ether_aton(), ether_ntohost(), ether_hostton(), and
     ether_line() functions were adopted from SunOS and appeared in NetBSD 0.9
     b.

BUGS
     The data space used by these functions is static; if future use requires
     the data, it should be copied before any subsequent calls to these func-
     tions overwrite it.

BSD                            December 16, 1993                           BSD

143.5. getaddrinfo

GETADDRINFO(3)           BSD Library Functions Manual           GETADDRINFO(3)

NAME
     getaddrinfo, freeaddrinfo, gai_strerror -- nodename-to-address transla-
     tion in protocol-independent manner

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>
     #include <netdb.h>

     int
     getaddrinfo(const char *nodename, const char *servname,
         const struct addrinfo *hints, struct addrinfo **res);

     void
     freeaddrinfo(struct addrinfo *ai);

     char *
     gai_strerror(int ecode);

DESCRIPTION
     The getaddrinfo() function is defined for protocol-independent nodename-
     to-address translation.  It performs the functionality of
     gethostbyname(3) and getservbyname(3), but in a more sophisticated man-
     ner.

     The addrinfo structure is defined as a result of including the <netdb.h>
     header:

     struct addrinfo {                                                  *
          int     ai_flags;     /* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST */
          int     ai_family;    /* PF_xxx */
          int     ai_socktype;  /* SOCK_xxx */
          int     ai_protocol;  /* 0 or IPPROTO_xxx for IPv4 and IPv6 */
          size_t  ai_addrlen;   /* length of ai_addr */
          char   *ai_canonname; /* canonical name for nodename */
          struct sockaddr  *ai_addr; /* binary address */
          struct addrinfo  *ai_next; /* next structure in linked list */
     };

     The nodename and servname arguments are pointers to NUL-terminated
     strings or NULL.  One or both of these two arguments must be a non-null
     pointer.  In the normal client scenario, both the nodename and servname
     are specified.  In the normal server scenario, only the servname is spec-
     ified.  A non-null nodename string can be either a node name or a numeric
     host address string (i.e., a dotted-decimal IPv4 address or an IPv6 hex
     address).  A non-null servname string can be either a service name or a
     decimal port number.

     The caller can optionally pass an addrinfo structure, pointed to by the
     third argument, to provide hints concerning the type of socket that the
     caller supports.  In this hints structure all members other than
     ai_flags, ai_family, ai_socktype, and ai_protocol must be zero or a null
     pointer.  A value of PF_UNSPEC for ai_family means the caller will accept
     any protocol family.  A value of 0 for ai_socktype means the caller will
     accept any socket type.  A value of 0 for ai_protocol means the caller
     will accept any protocol.  For example, if the caller handles only TCP
     and not UDP, then the ai_socktype member of the hints structure should be
     set to SOCK_STREAM when getaddrinfo() is called.  If the caller handles
     only IPv4 and not IPv6, then the ai_family member of the hints structure
     should be set to PF_INET when getaddrinfo() is called.  If the third
     argument to getaddrinfo() is a null pointer, this is the same as if the
     caller had filled in an addrinfo structure initialized to zero with
     ai_family set to PF_UNSPEC.

     Upon successful return a pointer to a linked list of one or more addrinfo
     structures is returned through the final argument.  The caller can
     process each addrinfo structure in this list by following the ai_next
     pointer, until a null pointer is encountered.  In each returned addrinfo
     structure the three members ai_family, ai_socktype, and ai_protocol are
     the corresponding arguments for a call to the socket() function.  In each
     addrinfo structure the ai_addr member points to a filled-in socket
     address structure whose length is specified by the ai_addrlen member.

     If the AI_PASSIVE bit is set in the ai_flags member of the hints struc-
     ture, then the caller plans to use the returned socket address structure
     in a call to bind().  In this case, if the nodename argument is a null
     pointer, then the IP address portion of the socket address structure will
     be set to INADDR_ANY for an IPv4 address or IN6ADDR_ANY_INIT for an IPv6
     address.

     If the AI_PASSIVE bit is not set in the ai_flags member of the hints
     structure, then the returned socket address structure will be ready for a
     call to connect() (for a connection-oriented protocol) or either
     connect(), sendto(), or sendmsg() (for a connectionless protocol).  In
     this case, if the nodename argument is a null pointer, then the IP
     address portion of the socket address structure will be set to the loop-
     back address.

     If the AI_CANONNAME bit is set in the ai_flags member of the hints struc-
     ture, then upon successful return the ai_canonname member of the first
     addrinfo structure in the linked list will point to a NUL-terminated
     string containing the canonical name of the specified nodename.

     If the AI_NUMERICHOST bit is set in the ai_flags member of the hints
     structure, then a non-null nodename string must be a numeric host address
     string.  Otherwise an error of EAI_NONAME is returned.  This flag pre-
     vents any type of name resolution service (e.g., the DNS) from being
     called.

     The arguments to getaddrinfo() must sufficiently be consistent and unam-
     biguous.  Here are pitfall cases you may encounter:

     +   getaddrinfo() will raise an error if members of the hints structure
         are not consistent.  For example, for internet address families,
         getaddrinfo() will raise an error if you specify SOCK_STREAM to
         ai_socktype while you specify IPPROTO_UDP to ai_protocol.

     +   If you specify a servname which is defined only for certain
         ai_socktype, getaddrinfo() will raise an error because the arguments
         are not consistent.  For example, getaddrinfo() will raise an error
         if you ask for ``tftp'' service on SOCK_STREAM.

     +   For internet address families, if you specify servname while you set
         ai_socktype to SOCK_RAW, getaddrinfo() will raise an error, because
         service names are not defined for the internet SOCK_RAW space.

     +   If you specify a numeric servname, while leaving ai_socktype and
         ai_protocol unspecified, getaddrinfo() will raise an error.  This is
         because the numeric servname does not identify any socket type, and
         getaddrinfo() is not allowed to glob the argument in such case.

     All of the information returned by getaddrinfo() is dynamically allo-
     cated: the addrinfo structures, the socket address structures, and canon-
     ical node name strings pointed to by the addrinfo structures.  To return
     this information to the system the function freeaddrinfo() is called.
     The addrinfo structure pointed to by the ai argument is freed, along with
     any dynamic storage pointed to by the structure.  This operation is
     repeated until a NULL ai_next pointer is encountered.

     To aid applications in printing error messages based on the EAI_xxx codes
     returned by getaddrinfo(), gai_strerror() is defined.  The argument is
     one of the EAI_xxx values defined earlier and the return value points to
     a string describing the error.  If the argument is not one of the EAI_xxx
     values, the function still returns a pointer to a string whose contents
     indicate an unknown error.

   Extension for scoped IPv6 address
     The implementation allows experimental numeric IPv6 address notation with
     scope identifier.  By appending the percent character and scope identi-
     fier to addresses, you can fill sin6_scope_id field for addresses.  This
     would make management of scoped address easier, and allows cut-and-paste
     input of scoped address.

     At this moment the code supports only link-local addresses with the for-
     mat.  Scope identifier is hardcoded to name of hardware interface associ-
     ated with the link.  (such as ne0).  Example would be like
     ``fe80::1%ne0'', which means ``fe80::1 on the link associated with ne0
     interface''.

     The implementation is still very experimental and non-standard.  The cur-
     rent implementation assumes one-by-one relationship between interface and
     link, which is not necessarily true from the specification.

EXAMPLES
     The following code tries to connect to ``www.kame.net'' service ``http''.
     via stream socket.  It loops through all the addresses available, regard-
     less from address family.  If the destination resolves to IPv4 address,
     it will use AF_INET socket.  Similarly, if it resolves to IPv6, AF_INET6
     socket is used.  Observe that there is no hardcoded reference to particu-
     lar address family.  The code works even if getaddrinfo returns addresses
     that are not IPv4/v6.

           struct addrinfo hints, *res, *res0;
           int error;
           int s;
           const char *cause = NULL;

           memset(&hints, 0, sizeof(hints));
           hints.ai_family = PF_UNSPEC;
           hints.ai_socktype = SOCK_STREAM;
           error = getaddrinfo("www.kame.net", "http", &hints, &res0);
           if (error) {
                   errx(1, "%s", gai_strerror(error));
                   /*NOTREACHED*/
           }
           s = -1;
           for (res = res0; res; res = res->ai_next) {
                   s = socket(res->ai_family, res->ai_socktype,
                       res->ai_protocol);
                   if (s < 0) {
                           cause = "socket";
                           continue;
                   }

                   if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
                           cause = "connect";
                           close(s);
                           s = -1;
                           continue;
                   }

                   break;  /* okay we got one */
           }
           if (s < 0) {
                   err(1, cause);
                   /*NOTREACHED*/
           }
           freeaddrinfo(res0);

     The following example tries to open a wildcard listening socket onto ser-
     vice ``http'', for all the address families available.

           struct addrinfo hints, *res, *res0;
           int error;
           int s[MAXSOCK];
           int nsock;
           const char *cause = NULL;

           memset(&hints, 0, sizeof(hints));
           hints.ai_family = PF_UNSPEC;
           hints.ai_socktype = SOCK_STREAM;
           hints.ai_flags = AI_PASSIVE;
           error = getaddrinfo(NULL, "http", &hints, &res0);
           if (error) {
                   errx(1, "%s", gai_strerror(error));
                   /*NOTREACHED*/
           }
           nsock = 0;
           for (res = res0; res && nsock < MAXSOCK; res = res->ai_next) {
                   s[nsock] = socket(res->ai_family, res->ai_socktype,
                       res->ai_protocol);
                   if (s[nsock] < 0) {
                           cause = "socket";
                           continue;
                   }

                   if (bind(s[nsock], res->ai_addr, res->ai_addrlen) < 0) {
                           cause = "bind";
                           close(s[nsock]);
                           continue;
                   }
                   (void) listen(s[nsock], 5);

                   nsock++;
           }
           if (nsock == 0) {
                   err(1, cause);
                   /*NOTREACHED*/
           }
           freeaddrinfo(res0);

DIAGNOSTICS
     Error return status from getaddrinfo() is zero on success and non-zero on
     errors.  Non-zero error codes are defined in <netdb.h>, and as follows:

     EAI_ADDRFAMILY  Address family for nodename not supported.
     EAI_AGAIN       Temporary failure in name resolution.
     EAI_BADFLAGS    Invalid value for ai_flags.
     EAI_FAIL        Non-recoverable failure in name resolution.
     EAI_FAMILY      ai_family not supported.
     EAI_MEMORY      Memory allocation failure.
     EAI_NODATA      No address associated with nodename.
     EAI_NONAME      nodename nor servname provided, or not known.
     EAI_SERVICE     servname not supported for ai_socktype.
     EAI_SOCKTYPE    ai_socktype not supported.
     EAI_SYSTEM      System error returned in errno.

     If called with proper argument, gai_strerror() returns a pointer to a
     string describing the given error code.  If the argument is not one of
     the EAI_xxx values, the function still returns a pointer to a string
     whose contents indicate an unknown error.

SEE ALSO
     getnameinfo(3), gethostbyname(3), getservbyname(3), hosts(5),
     resolv.conf(5), services(5), hostname(7), named(8)

     R. Gilligan, S. Thomson, J. Bound, and W. Stevens, Basic Socket Interface
     Extensions for IPv6, RFC2553, March 1999.

     Tatsuya Jinmei and Atsushi Onoe, An Extension of Format for IPv6 Scoped
     Addresses, internet draft, draft-ietf-ipngwg-scopedaddr-format-02.txt,
     work in progress material.

     Craig Metz, "Protocol Independence Using the Sockets API", Proceedings of
     the freenix track: 2000 USENIX annual technical conference, June 2000.

HISTORY
     The implementation first appeared in WIDE Hydrangea IPv6 protocol stack
     kit.

STANDARDS
     The getaddrinfo() function is defined in IEEE POSIX 1003.1g draft speci-
     fication, and documented in ``Basic Socket Interface Extensions for
     IPv6'' (RFC2553).

BUGS
     The text was shamelessly copied from RFC2553.

BSD                              May 25, 1995                              BSD

143.6. gethostbyname

GETHOSTBYNAME(3)         BSD Library Functions Manual         GETHOSTBYNAME(3)

NAME
     gethostbyname, gethostbyname2, gethostbyaddr, gethostent, sethostent,
     endhostent, hstrerror, herror -- get network host entry

SYNOPSIS
     #include <netdb.h>
     extern int h_errno;

     struct hostent *
     gethostbyname(const char *name);

     struct hostent *
     gethostbyname2(const char *name, int af);

     struct hostent *
     gethostbyaddr(const char *addr, int len, int af);

     struct hostent *
     gethostent(void);

     void
     sethostent(int stayopen);

     void
     endhostent(void);

     void
     herror(const char *string);

     const char *
     hstrerror(int err);

DESCRIPTION
     The gethostbyname() and gethostbyaddr() functions each return a pointer
     to an object with the following structure describing an internet host
     referenced by name or by address, respectively.  This structure contains
     either information obtained from the name server (i.e., resolver(3) and
     named(8)), broken-out fields from a line in /etc/hosts, or database
     entries supplied by the yp(8) system.  resolv.conf(5) describes how the
     particular database is chosen.

     struct  hostent {
             char    *h_name;        /* official name of host */
             char    **h_aliases;    /* alias list */
             int     h_addrtype;     /* host address type */
             int     h_length;       /* length of address */
             char    **h_addr_list;  /* list of addresses from name server */
     };
     #define h_addr  h_addr_list[0]  /* address, for backward compatibility */

     The members of this structure are:

     h_name       Official name of the host.

     h_aliases    A zero-terminated array of alternate names for the host.

     h_addrtype   The type of address being returned.

     h_length     The length, in bytes, of the address.

     h_addr_list  A zero-terminated array of network addresses for the host.
                  Host addresses are returned in network byte order.

     h_addr       The first address in h_addr_list; this is for backward com-
                  patibility.

     The function gethostbyname() will search for the named host in the cur-
     rent domain and its parents using the search lookup semantics detailed in
     resolv.conf(5) and hostname(7).

     gethostbyname2() is an advanced form of gethostbyname() which allows
     lookups in address families other than AF_INET, for example AF_INET6.

     The gethostbyaddr() function will search for the specified address of
     length len in the address family af.  The only address family currently
     supported is AF_INET.

     The sethostent() function may be used to request the use of a connected
     TCP socket for queries.  If the stayopen flag is non-zero, this sets the
     option to send all queries to the name server using TCP and to retain the
     connection after each call to gethostbyname() or gethostbyaddr().  Other-
     wise, queries are performed using UDP datagrams.

     The endhostent() function closes the TCP connection.

     The herror() function prints an error message describing the failure.  If
     its argument string is non-null, it is prepended to the message string
     and separated from it by a colon (`:') and a space.  The error message is
     printed with a trailing newline.  The contents of the error message is
     the same as that returned by hstrerror() with argument h_errno.

FILES
     /etc/hosts
     /etc/resolv.conf

DIAGNOSTICS
     Error return status from gethostbyname(), gethostbyname2(), and
     gethostbyaddr() is indicated by return of a null pointer.  The external
     integer h_errno may then be checked to see whether this is a temporary
     failure or an invalid or unknown host.

     The variable h_errno can have the following values:

     HOST_NOT_FOUND  No such host is known.

     TRY_AGAIN       This is usually a temporary error and means that the
                     local server did not receive a response from an authori-
                     tative server.  A retry at some later time may succeed.

     NO_RECOVERY     Some unexpected server failure was encountered.  This is
                     a non-recoverable error.

     NO_DATA         The requested name is valid but does not have an IP
                     address; this is not a temporary error.  This means that
                     the name is known to the name server but there is no
                     address associated with this name.  Another type of
                     request to the name server using this domain name will
                     result in an answer; for example, a mail-forwarder may be
                     registered for this domain.

SEE ALSO
     resolver(3), getaddrinfo(3), getnameinfo(3), hosts(5), resolv.conf(5),
     hostname(7), named(8)

CAVEAT
     If the search routines in resolv.conf(5) decide to read the /etc/hosts
     file, gethostent() and other functions will read the next line of the
     file, re-opening the file if necessary.

     The sethostent() function opens and/or rewinds the file /etc/hosts.  If
     the stayopen argument is non-zero, the file will not be closed after each
     call to gethostbyname(), gethostbyname2(), or gethostbyaddr().

     The endhostent() function closes the file.

HISTORY
     The herror() function appeared in 4.3BSD.  The endhostent(),
     gethostbyaddr(), gethostbyname(), gethostent(), and sethostent() func-
     tions appeared in 4.2BSD.

BUGS
     These functions use static data storage; if the data is needed for future
     use, it should be copied before any subsequent calls overwrite it.  Only
     the Internet address formats are currently understood.

     YP does not support any address families other than AF_INET and uses the
     traditional database format.

BSD                             March 13, 1997                             BSD

143.7. getifaddrs

GETIFADDRS(3)            BSD Library Functions Manual            GETIFADDRS(3)

NAME
     getifaddrs -- get interface addresses

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>
     #include <ifaddrs.h>

     int
     getifaddrs(struct ifaddrs **ifap);

     void
     freeifaddrs(struct ifaddrs *ifap);

DESCRIPTION
     The getifaddrs() function stores a reference to a linked list of the net-
     work interfaces on the local machine in the memory referenced by ifap.
     The list consists of ifaddrs structures, as defined in the include file
     <ifaddrs.h>.  The ifaddrs structure contains at least the following
     entries:

         struct ifaddrs   *ifa_next;         /* Pointer to next struct */
         char             *ifa_name;         /* Interface name */
         u_int             ifa_flags;        /* Interface flags */
         struct sockaddr  *ifa_addr;         /* Interface address */
         struct sockaddr  *ifa_netmask;      /* Interface netmask */
         struct sockaddr  *ifa_broadaddr;    /* Interface broadcast address */
         struct sockaddr  *ifa_dstaddr;      /* P2P interface destination */
         void             *ifa_data;         /* Address specific data */

     ifa_next
             Contains a pointer to the next structure on the list.  This field
             is set to NULL in last structure on the list.

     ifa_name
             Contains the interface name.

     ifa_flags
             Contains the interface flags, as set by ifconfig(8).

     ifa_addr
             References either the address of the interface or the link level
             address of the interface, if one exists, otherwise it is NULL.
             (The sa_family field of the ifa_addr field should be consulted to
             determine the format of the ifa_addr address.)

     ifa_netmask
             References the netmask associated with ifa_addr, if one is set,
             otherwise it is NULL.

     ifa_broadaddr
             This field, which should only be referenced for non-P2P inter-
             faces, references the broadcast address associated with ifa_addr,
             if one exists, otherwise it is NULL.

     ifa_dstaddr
             References the destination address on a P2P interface, if one
             exists, otherwise it is NULL.

     ifa_data
             References address family specific data.  For AF_LINK addresses
             it contains a pointer to the struct if_data (as defined in
             include file <net/if.h>) which contains various interface
             attributes and statistics.  For all other address families, it
             contains a pointer to the struct ifa_data (as defined in include
             file <net/if.h>) which contains per-address interface statistics.

     The data returned by getifaddrs() is dynamically allocated and should be
     freed using freeifaddrs() when no longer needed.

RETURN VALUES
     Upon successful completion, a value of 0 is returned.  Otherwise, a value
     of -1 is returned and errno is set to indicate the error.

ERRORS
     The getifaddrs() may fail and set errno for any of the errors specified
     for the library routines ioctl(2), socket(2), malloc(3), or sysctl(3).

BUGS
     If both <net/if.h> and <ifaddrs.h> are being included, <net/if.h> must be
     included before <ifaddrs.h>.

SEE ALSO
     ioctl(2), socket(2), sysctl(3), networking(4), ifconfig(8)

HISTORY
     The getifaddrs() function first appeared in BSDI BSD/OS.  The function is
     supplied on OpenBSD since OpenBSD 2.7.

                               September 3, 2013

143.8. getnameinfo

GETNAMEINFO(3)           BSD Library Functions Manual           GETNAMEINFO(3)

NAME
     getnameinfo -- address-to-nodename translation in protocol-independent
     manner

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>
     #include <netdb.h>

     int
     getnameinfo(const struct sockaddr *sa, socklen_t salen, char *host,
         size_t hostlen, char *serv, size_t servlen, int flags);

DESCRIPTION
     The getnameinfo() function is defined for protocol-independent address-
     to-nodename translation.  Its functionality is a reverse conversion of
     getaddrinfo(3), and implements similar functionality with
     gethostbyaddr(3) and getservbyport(3) in more sophisticated manner.

     This function looks up an IP address and port number provided by the
     caller in the DNS and system-specific database, and returns text strings
     for both in buffers provided by the caller.  The function indicates suc-
     cessful completion by a zero return value; a non-zero return value indi-
     cates failure.

     The first argument, sa, points to either a sockaddr_in structure (for
     IPv4) or a sockaddr_in6 structure (for IPv6) that holds the IP address
     and port number.  The salen argument gives the length of the sockaddr_in
     or sockaddr_in6 structure.

     The function returns the nodename associated with the IP address in the
     buffer pointed to by the host argument.  The caller provides the size of
     this buffer via the hostlen argument.  The service name associated with
     the port number is returned in the buffer pointed to by serv, and the
     servlen argument gives the length of this buffer.  The caller specifies
     not to return either string by providing a zero value for the hostlen or
     servlen arguments.  Otherwise, the caller must provide buffers large
     enough to hold the nodename and the service name, including the terminat-
     ing null characters.

     Unfortunately most systems do not provide constants that specify the max-
     imum size of either a fully-qualified domain name or a service name.
     Therefore to aid the application in allocating buffers for these two
     returned strings the following constants are defined in <netdb.h>:

     #define NI_MAXHOST    MAXHOSTNAMELEN
     #define NI_MAXSERV    32

     The first value is actually defined as the constant MAXDNAME in recent
     versions of BIND's <arpa/nameser.h> header (older versions of BIND define
     this constant to be 256) and the second is a guess based on the services
     listed in the current Assigned Numbers RFC.

     The final argument is a flag that changes the default actions of this
     function.  By default the fully-qualified domain name (FQDN) for the host
     is looked up in the DNS and returned.  If the flag bit NI_NOFQDN is set,
     only the nodename portion of the FQDN is returned for local hosts.

     If the flag bit NI_NUMERICHOST is set, or if the host's name cannot be
     located in the DNS, the numeric form of the host's address is returned
     instead of its name (e.g., by calling inet_ntop() instead of
     gethostbyaddr()).  If the flag bit NI_NAMEREQD is set, an error is
     returned if the host's name cannot be located in the DNS.

     If the flag bit NI_NUMERICSERV is set, the numeric form of the service
     address is returned (e.g., its port number) instead of its name.  The two
     NI_NUMERICxxx flags are required to support the -n flag that many com-
     mands provide.

     A fifth flag bit, NI_DGRAM, specifies that the service is a datagram ser-
     vice, and causes getservbyport() to be called with a second argument of
     "udp" instead of its default of "tcp".  This is required for the few
     ports (512-514) that have different services for UDP and TCP.

     These NI_xxx flags are defined in <netdb.h>.

   Extension for scoped IPv6 address
     The implementation allows experimental numeric IPv6 address notation with
     scope identifier.  IPv6 link-local address will appear as string like
     ``fe80::1%ne0'', if NI_WITHSCOPEID bit is enabled in flags argument.
     Refer to getaddrinfo(3) for the notation.

EXAMPLES
     The following code tries to get numeric hostname, and service name, for
     given socket address.  Observe that there is no hardcoded reference to
     particular address family.

           struct sockaddr *sa;    /* input */
           char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];

           if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), sbuf,
               sizeof(sbuf), NI_NUMERICHOST | NI_NUMERICSERV)) {
                   errx(1, "could not get numeric hostname");
                   /*NOTREACHED*/
           }
           printf("host=%s, serv=%s\n", hbuf, sbuf);

     The following version checks if the socket address has reverse address
     mapping.

           struct sockaddr *sa;    /* input */
           char hbuf[NI_MAXHOST];

           if (getnameinfo(sa, sa->sa_len, hbuf, sizeof(hbuf), NULL, 0,
               NI_NAMEREQD)) {
                   errx(1, "could not resolve hostname");
                   /*NOTREACHED*/
           }
           printf("host=%s\n", hbuf);

DIAGNOSTICS
     The function indicates successful completion by a zero return value; a
     non-zero return value indicates failure.  Error codes are as below:

     EAI_AGAIN          The name could not be resolved at this time.  Future
                        attempts may succeed.

     EAI_BADFLAGS       The flags had an invalid value.

     EAI_FAIL           A non-recoverable error occurred.

     EAI_FAMILY         The address family was not recognized or the address
                        length was invalid for the specified family.

     EAI_MEMORY         There was a memory allocation failure.

     EAI_NONAME         The name does not resolve for the supplied parameters.
                        NI_NAMEREQD is set and the host's name cannot be
                        located, or both nodename and servname were null.

     EAI_SYSTEM         A system error occurred.  The error code can be found
                        in errno.

SEE ALSO
     getaddrinfo(3), gethostbyaddr(3), getservbyport(3), hosts(5),
     resolv.conf(5), services(5), hostname(7), named(8)

     R. Gilligan, S. Thomson, J. Bound, and W. Stevens, Basic Socket Interface
     Extensions for IPv6, RFC2553, March 1999.

     Tatsuya Jinmei and Atsushi Onoe, An Extension of Format for IPv6 Scoped
     Addresses, internet draft, draft-ietf-ipngwg-scopedaddr-format-02.txt,
     work in progress material.

     Craig Metz, "Protocol Independence Using the Sockets API", Proceedings of
     the freenix track: 2000 USENIX annual technical conference, June 2000.

HISTORY
     The implementation first appeared in WIDE Hydrangea IPv6 protocol stack
     kit.

STANDARDS
     The getaddrinfo() function is defined IEEE POSIX 1003.1g draft specifica-
     tion, and documented in ``Basic Socket Interface Extensions for IPv6''
     (RFC2553).

BUGS
     The current implementation is not thread-safe.

     The text was shamelessly copied from RFC2553.

     OpenBSD intentionally uses different NI_MAXHOST value from what RFC2553
     suggests, to avoid buffer length handling mistakes.

BSD                              May 25, 1995                              BSD

143.9. getnetent

GETNETENT(3)             BSD Library Functions Manual             GETNETENT(3)

NAME
     getnetent, getnetbyaddr, getnetbyname, setnetent, endnetent -- get net-
     work entry

SYNOPSIS
     #include <netdb.h>

     struct netent *
     getnetent(void);

     struct netent *
     getnetbyname(char *name);

     struct netent *
     getnetbyaddr(in_addr_t net, int type);

     void
     setnetent(int stayopen);

     void
     endnetent(void);

DESCRIPTION
     The getnetent(), getnetbyname(), and getnetbyaddr() functions each return
     a pointer to an object with the following structure containing the bro-
     ken-out fields of a line in the network database, /etc/networks.

           struct  netent {
                   char            *n_name;        /* official name of net */
                   char            **n_aliases;    /* alias list */
                   int             n_addrtype;     /* net number type */
                   in_addr_t       n_net;          /* net number */
           };

     The members of this structure are:

     n_name      The official name of the network.

     n_aliases   A zero-terminated list of alternate names for the network.

     n_addrtype  The type of the network number returned; currently only
                 AF_INET.

     n_net       The network number.  Network numbers are returned in machine
                 byte order.

     The getnetent() function reads the next line of the file, opening the
     file if necessary.

     The setnetent() function opens and rewinds the file.  If the stayopen
     flag is non-zero, the net database will not be closed after each call to
     getnetbyname() or getnetbyaddr().

     The endnetent() function closes the file.

     The getnetbyname() and getnetbyaddr() functions search the domain name
     server if the system is configured to use one.  If the search fails, or
     no name server is configured, they sequentially search from the beginning
     of the file until a matching net name or net address and type is found,
     or until EOF is encountered.  Network numbers are supplied in host order.

FILES
     /etc/networks

DIAGNOSTICS
     Null pointer (0) returned on EOF or error.

SEE ALSO
     resolver(3), networks(5)

HISTORY
     The getnetent(), getnetbyaddr(), getnetbyname(), setnetent(), and
     endnetent() functions appeared in 4.2BSD.

BUGS
     The data space used by these functions is static; if future use requires
     the data, it should be copied before any subsequent calls to these func-
     tions overwrite it.  Only Internet network numbers are currently under-
     stood.  Expecting network numbers to fit in no more than 32 bits is
     naive.

BSD                             March 13, 1997                             BSD

143.10. getprotoent

GETPROTOENT(3)           BSD Library Functions Manual           GETPROTOENT(3)

NAME
     getprotoent, getprotobynumber, getprotobyname, setprotoent, endprotoent
     -- get protocol entry

SYNOPSIS
     #include <netdb.h>

     struct protoent *
     getprotoent(void);

     struct protoent *
     getprotobyname(char *name);

     struct protoent *
     getprotobynumber(int proto);

     void
     setprotoent(int stayopen);

     void
     endprotoent(void);

DESCRIPTION
     The getprotoent(), getprotobyname(), and getprotobynumber() functions
     each return a pointer to an object with the following structure contain-
     ing the broken-out fields of a line in the network protocol database,
     /etc/protocols.


           struct  protoent {
                   char    *p_name;        /* official name of protocol */
                   char    **p_aliases;    /* alias list */
                   int     p_proto;        /* protocol number */
           };

     The members of this structure are:

     p_name     The official name of the protocol.

     p_aliases  A zero-terminated list of alternate names for the protocol.

     p_proto    The protocol number.

     The getprotoent() function reads the next line of the file, opening the
     file if necessary.

     The setprotoent() function opens and rewinds the file.  If the stayopen
     flag is non-zero, the net database will not be closed after each call to
     getprotobyname() or getprotobynumber().

     The endprotoent() function closes the file.

     The getprotobyname() and getprotobynumber() functions sequentially search
     from the beginning of the file until a matching protocol name or protocol
     number is found, or until EOF is encountered.

RETURN VALUES
     Null pointer (0) returned on EOF or error.

FILES
     /etc/protocols

SEE ALSO
     protocols(5)

HISTORY
     The getprotoent(), getprotobynumber(), getprotobyname(), setprotoent(),
     and endprotoent() functions appeared in 4.2BSD.

BUGS
     These functions use a static data space; if the data is needed for future
     use, it should be copied before any subsequent calls overwrite it.  Only
     the Internet protocols are currently understood.

BSD                              June 4, 1993                              BSD

143.11. getrrsetbyname

GETRRSETBYNAME(3)        BSD Library Functions Manual        GETRRSETBYNAME(3)

NAME
     getrrsetbyname -- retrieve DNS records

SYNOPSIS
     #include <netdb.h>

     int
     getrrsetbyname(const char *hostname, unsigned int rdclass,
         unsigned int rdtype, unsigned int flags, struct rrsetinfo **res);

     int
     freerrset(struct rrsetinfo **rrset);

DESCRIPTION
     getrrsetbyname() gets a set of resource records associated with a
     hostname, class and type.  hostname is a pointer a to null-terminated
     string.  The flags field is currently unused and must be zero.

     After a successful call to getrrsetbyname(), *res is a pointer to an
     rrsetinfo structure, containing a list of one or more rdatainfo struc-
     tures containing resource records and potentially another list of
     rdatainfo structures containing SIG resource records associated with
     those records.  The members rri_rdclass and rri_rdtype are copied from
     the parameters.  rri_ttl and rri_name are properties of the obtained
     rrset.  The resource records contained in rri_rdatas and rri_sigs are in
     uncompressed DNS wire format.  Properties of the rdataset are represented
     in the rri_flags bitfield. If the RRSET_VALIDATED bit is set, the data
     has been DNSSEC validated and the signatures verified.

     The following structures are used:

     struct  rdatainfo {
             unsigned int            rdi_length;     /* length of data */
             unsigned char           *rdi_data;      /* record data */
     };

     struct  rrsetinfo {
             unsigned int            rri_flags;      /* RRSET_VALIDATED … */
             unsigned int            rri_rdclass;    /* class number */
             unsigned int            rri_rdtype;     /* RR type number */
             unsigned int            rri_ttl;        /* time to live */
             unsigned int            rri_nrdatas;    /* size of rdatas array */
             unsigned int            rri_nsigs;      /* size of sigs array */
             char                    *rri_name;      /* canonical name */
             struct rdatainfo        *rri_rdatas;    /* individual records */
             struct rdatainfo        *rri_sigs;      /* individual signatures */
     };

     All of the information returned by getrrsetbyname() is dynamically allo-
     cated: the rrsetinfo and rdatainfo structures, and the canonical host
     name strings pointed to by the rrsetinfostructure. Memory allocated for
     the dynamically allocated structures created by a successful call to
     getrrsetbyname() is released by freerrset().  rrset is a pointer to a
     struct rrset created by a call to getrrsetbyname().

     If the EDNS0 option is activated in resolv.conf(3), getrrsetbyname() will
     request DNSSEC authentication using the EDNS0 DNSSEC OK (DO) bit.

RETURN VALUES
     getrrsetbyname() returns zero on success, and one of the following error
     codes if an error occurred:

     ERRSET_NONAME    the name does not exist
     ERRSET_NODATA    the name exists, but does not have data of the desired
                      type
     ERRSET_NOMEMORY  memory could not be allocated
     ERRSET_INVAL     a parameter is invalid
     ERRSET_FAIL      other failure

SEE ALSO
     resolver(3), resolv.conf(5), named(8)

AUTHORS
     Jakob Schlyter <jakob@openbsd.org>

HISTORY
     getrrsetbyname() first appeared in OpenBSD 3.0.  The API first appeared
     in ISC BIND version 9.

BUGS
     The data in *rdi_data should be returned in uncompressed wire format.
     Currently, the data is in compressed format and the caller can't uncom-
     press since it doesn't have the full message.

CAVEATS
     The RRSET_VALIDATED flag in rri_flags is set if the AD (autenticated
     data) bit in the DNS answer is set. This flag should not be trusted
     unless the transport between the nameserver and the resolver is secure
     (e.g. IPsec, trusted network, loopback communication).

BSD                              Oct 18, 2000                              BSD

143.12. getservent

GETSERVENT(3)            BSD Library Functions Manual            GETSERVENT(3)

NAME
     getservent, getservbyport, getservbyname, setservent, endservent -- get
     service entry

SYNOPSIS
     #include <netdb.h>

     struct servent *
     getservent(void);

     struct servent *
     getservbyname(char *name, char *proto);

     struct servent *
     getservbyport(int port, char *proto);

     void
     setservent(int stayopen);

     void
     endservent(void);

DESCRIPTION
     The getservent(), getservbyname(), and getservbyport() functions each
     return a pointer to an object with the following structure containing the
     broken-out fields of a line in the network services database,
     /etc/services.

           struct  servent {
                   char    *s_name;        /* official name of service */
                   char    **s_aliases;    /* alias list */
                   int     s_port;         /* port service resides at */
                   char    *s_proto;       /* protocol to use */
           };

     The members of this structure are:

     s_name     The official name of the service.

     s_aliases  A zero-terminated list of alternate names for the service.

     s_port     The port number at which the service resides.  Port numbers
                are returned in network byte order.

     s_proto    The name of the protocol to use when contacting the service.

     The getservent() function reads the next line of the file, opening the
     file if necessary.

     The setservent() function opens and rewinds the file.  If the stayopen
     flag is non-zero, the net database will not be closed after each call to
     getservbyname() or getservbyport().

     The endservent() function closes the file.

     The getservbyname() and getservbyport() functions sequentially search
     from the beginning of the file until a matching protocol name or port
     number (specified in network byte order) is found, or until EOF is
     encountered.  If a protocol name is also supplied (non-null), searches
     must also match the protocol.

FILES
     /etc/services

DIAGNOSTICS
     Null pointer (0) returned on EOF or error.

SEE ALSO
     getprotoent(3), services(5)

HISTORY
     The getservent(), getservbyport(), getservbyname(), setservent(), and
     endservent() functions appeared in 4.2BSD.

BUGS
     These functions use static data storage; if the data is needed for future
     use, it should be copied before any subsequent calls overwrite it.
     Expecting port numbers to fit in a 32-bit quantity is probably naive.

BSD                            January 12, 1994                            BSD

143.13. if_nametoindex

IF_NAMETOINDEX(3)        BSD Library Functions Manual        IF_NAMETOINDEX(3)

NAME
     if_nametoindex, if_indextoname, if_nameindex, if_freenameindex -- convert
     interface index to name, and vice versa

SYNOPSIS
     #include <net/if.h>

     unsigned int
     if_nametoindex(const char *ifname);

     char *
     if_indextoname(unsigned int ifindex, char *ifname);

     struct if_nameindex *
     if_nameindex(void);

     void
     if_freenameindex(struct if_nameindex *ptr);

DESCRIPTION
     These functions map interface indexes to interface names (such as
     ``lo0''), and vice versa.

     The if_nametoindex() function converts an interface name specified by the
     ifname argument to an interface index (positive integer value).  If the
     specified interface does not exist, 0 will be returned.

     if_indextoname() converts an interface index specified by the ifindex
     argument to an interface name.  The ifname argument must point to a buf-
     fer of at least IF_NAMESIZE bytes into which the interface name corre-
     sponding to the specified index is returned.  (IF_NAMESIZE is also
     defined in <net/if.h> and its value includes a terminating null byte at
     the end of the interface name.)  This pointer is also the return value of
     the function.  If there is no interface corresponding to the specified
     index, NULL is returned.

     if_nameindex() returns an array of if_nameindex structures.
     if_nametoindex is also defined in <net/if.h>, and is as follows:

     struct if_nameindex {
         unsigned int   if_index;  /* 1, 2, … */
         char          *if_name;   /* null terminated name: "le0", … */
     };

     The end of the array of structures is indicated by a structure with an
     if_index of 0 and an if_name of NULL.  The function returns a null
     pointer on error.  The memory used for this array of structures along
     with the interface names pointed to by the if_name members is obtained
     dynamically.  This memory is freed by the if_freenameindex() function.

     if_freenameindex() takes a pointer that was returned by if_nameindex() as
     argument (ptr), and it reclaims the region allocated.

DIAGNOSTICS
     if_nametoindex() returns 0 on error, positive integer on success.
     if_indextoname() and if_nameindex() return NULL on errors.

SEE ALSO
     R. Gilligan, S.  Thomson, J. Bound, and W. Stevens, ``Basic Socket Inter-
     face Extensions for IPv6,'' RFC2553, March 1999.

STANDARDS
     These functions are defined in ``Basic Socket Interface Extensions for
     IPv6'' (RFC2533).

BSD                              May 21, 1998                              BSD

143.14. inet

INET(3)                  BSD Library Functions Manual                  INET(3)

NAME
     inet_addr, inet_aton, inet_lnaof, inet_makeaddr, inet_netof,
     inet_network, inet_ntoa, inet_ntop, inet_pton -- Internet address manipu-
     lation routines

SYNOPSIS
     #include <sys/socket.h>
     #include <netinet/in.h>
     #include <arpa/inet.h>

     in_addr_t
     inet_addr(const char *cp);

     int
     inet_aton(const char *cp, struct in_addr *addr);

     in_addr_t
     inet_lnaof(struct in_addr in);

     struct in_addr
     inet_makeaddr(unsigned long net, unsigned long lna);

     in_addr_t
     inet_netof(struct in_addr in);

     in_addr_t
     inet_network(const char *cp);

     char *
     inet_ntoa(struct in_addr in);

     const char *
     inet_ntop(int af, const void *src, char *dst, size_t size);

     int
     inet_pton(int af, const char *src, void *dst);

DESCRIPTION
     The routines inet_aton(), inet_addr() and inet_network() interpret char-
     acter strings representing numbers expressed in the Internet standard `.'
     notation.  The inet_pton() function converts a presentation format
     address (that is, printable form as held in a character string) to net-
     work format (usually a struct in_addr or some other internal binary rep-
     resentation, in network byte order).  It returns 1 if the address was
     valid for the specified address family, or 0 if the address wasn't
     parseable in the specified address family, or -1 if some system error
     occurred (in which case errno will have been set).  This function is
     presently valid for AF_INET and AF_INET6.  The inet_aton() routine inter-
     prets the specified character string as an Internet address, placing the
     address into the structure provided.  It returns 1 if the string was suc-
     cessfully interpreted, or 0 if the string was invalid.  The inet_addr()
     and inet_network() functions return numbers suitable for use as Internet
     addresses and Internet network numbers, respectively.

     The function inet_ntop() converts an address from network format (usually
     a struct in_addr or some other binary form, in network byte order) to
     presentation format (suitable for external display purposes).  It returns
     NULL if a system error occurs (in which case, errno will have been set),
     or it returns a pointer to the destination string.  The routine
     inet_ntoa() takes an Internet address and returns an ASCII string repre-
     senting the address in `.' notation.  The routine inet_makeaddr() takes
     an Internet network number and a local network address and constructs an
     Internet address from it.  The routines inet_netof() and inet_lnaof()
     break apart Internet host addresses, returning the network number and
     local network address part, respectively.

     All Internet addresses are returned in network order (bytes ordered from
     left to right).  All network numbers and local address parts are returned
     as machine format integer values.

INTERNET ADDRESSES (IP VERSION 4)
     Values specified using the `.' notation take one of the following forms:

           a.b.c.d
           a.b.c
           a.b
           a

     When four parts are specified, each is interpreted as a byte of data and
     assigned, from left to right, to the four bytes of an Internet address.
     Note that when an Internet address is viewed as a 32-bit integer quantity
     on a system that uses little-endian byte order (such as the Intel 386,
     486 and Pentium processors) the bytes referred to above appear as
     ``d.c.b.a''.  That is, little-endian bytes are ordered from right to
     left.

     When a three part address is specified, the last part is interpreted as a
     16-bit quantity and placed in the rightmost two bytes of the network
     address.  This makes the three part address format convenient for speci-
     fying Class B network addresses as ``128.net.host''.

     When a two part address is supplied, the last part is interpreted as a
     24-bit quantity and placed in the rightmost three bytes of the network
     address.  This makes the two part address format convenient for specify-
     ing Class A network addresses as ``net.host''.

     When only one part is given, the value is stored directly in the network
     address without any byte rearrangement.

     All numbers supplied as ``parts'' in a `.' notation may be decimal,
     octal, or hexadecimal, as specified in the C language (i.e., a leading 0x
     or 0X implies hexadecimal; otherwise, a leading 0 implies octal; other-
     wise, the number is interpreted as decimal).

INTERNET ADDRESSES (IP VERSION 6)
     In order to support scoped IPv6 addresses, getaddrinfo(3) and
     getnameinfo(3) are recommended rather than the functions presented here.

     The presentation format of an IPv6 address is given in [RFC1884 2.2]:

     There are three conventional forms for representing IPv6 addresses as
     text strings:

     1.   The preferred form is x:x:x:x:x:x:x:x, where the 'x's are the hexa-
          decimal values of the eight 16-bit pieces of the address.  Examples:

                FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
                1080:0:0:0:8:800:200C:417A

          Note that it is not necessary to write the leading zeros in an indi-
          vidual field, but there must be at least one numeral in every field
          (except for the case described in 2.).

     2.   Due to the method of allocating certain styles of IPv6 addresses, it
          will be common for addresses to contain long strings of zero bits.
          In order to make writing addresses

          containing zero bits easier a special syntax is available to com-
          press the zeros.  The use of ``::'' indicates multiple groups of 16
          bits of zeros.  The ``::'' can only appear once in an address.  The
          ``::'' can also be used to compress the leading and/or trailing
          zeros in an address.

          For example the following addresses:

                1080:0:0:0:8:800:200C:417A  a unicast address
                FF01:0:0:0:0:0:0:43         a multicast address
                0:0:0:0:0:0:0:1             the loopback address
                0:0:0:0:0:0:0:0             the unspecified addresses

          may be represented as:

                1080::8:800:200C:417A       a unicast address
                FF01::43                    a multicast address
                ::1                         the loopback address
                ::                          the unspecified addresses

     3.   An alternative form that is sometimes more convenient when dealing
          with a mixed environment of IPv4 and IPv6 nodes is
          x:x:x:x:x:x:d.d.d.d, where the 'x's are the hexadecimal values of
          the six high-order 16-bit pieces of the address, and the 'd's are
          the decimal values of the four low-order 8-bit pieces of the address
          (standard IPv4 representation).  Examples:

                0:0:0:0:0:0:13.1.68.3
                0:0:0:0:0:FFFF:129.144.52.38

          or in compressed form:

                ::13.1.68.3
                ::FFFF:129.144.52.38

DIAGNOSTICS
     The constant INADDR_NONE is returned by inet_addr() and inet_network()
     for malformed requests.

SEE ALSO
     byteorder(3), gethostbyname(3), getnetent(3), inet_net(3), hosts(5),
     networks(5)

STANDARDS
     The inet_ntop and inet_pton functions conforms to the IETF IPv6 BSD API
     and address formatting specifications.  Note that inet_pton does not
     accept 1-, 2-, or 3-part dotted addresses; all four parts must be speci-
     fied.  This is a narrower input set than that accepted by inet_aton.

HISTORY
     The inet_addr, inet_network, inet_makeaddr, inet_lnaof and inet_netof
     functions appeared in 4.2BSD.  The inet_aton and inet_ntoa functions
     appeared in 4.3BSD.  The inet_pton and inet_ntop functions appeared in
     BIND 4.9.4.

BUGS
     The value INADDR_NONE (0xffffffff) is a valid broadcast address, but
     inet_addr() cannot return that value without indicating failure.  Also,
     inet_addr() should have been designed to return a struct in_addr.  The
     newer inet_aton() function does not share these problems, and almost all
     existing code should be modified to use inet_aton() instead.

     The problem of host byte ordering versus network byte ordering is confus-
     ing.

     The string returned by inet_ntoa() resides in a static memory area.

BSD                              June 18, 1997                             BSD

143.15. inet6_option_space

INET6_OPTION_SPACE(3)    BSD Library Functions Manual    INET6_OPTION_SPACE(3)

NAME
     inet6_option_space, inet6_option_init, inet6_option_append,
     inet6_option_alloc, inet6_option_next, inet6_option_find -- IPv6 Hop-by-
     Hop and Destination Options manipulation

SYNOPSIS
     #include <netinet/in.h>

     int
     inet6_option_space(int nbytes);

     int
     inet6_option_init(void *bp, struct cmsghdr **cmsgp, int type);

     int
     inet6_option_append(struct cmsghdr *cmsg, const u_int8_t *typep,
         int multx, int plusy);

     u_int8_t *
     inet6_option_alloc(struct cmsghdr *cmsg, int datalen, int multx,
         int plusy);;

     int
     inet6_option_next(const struct cmsghdr *cmsg, u_int8_t **tptrp);

     int
     inet6_option_find(const struct cmsghdr *cmsg, u_int8_t **tptrp,
         int type);

DESCRIPTION
     Building and parsing the Hop-by-Hop and Destination options is compli-
     cated due to alignment constranints, padding and ancillary data manipula-
     tion.  RFC2292 defines a set of functions to help the application.  The
     function prototypes for these functions are all in the <netinet/in.h>
     header.

   inet6_option_space
     inet6_option_space() returns the number of bytes required to hold an
     option when it is stored as ancillary data, including the cmsghdr struc-
     ture at the beginning, and any padding at the end (to make its size a
     multiple of 8 bytes).  The argument is the size of the structure defining
     the option, which must include any pad bytes at the beginning (the value
     y in the alignment term ``xn + y''), the type byte, the length byte, and
     the option data.

     Note: If multiple options are stored in a single ancillary data object,
     which is the recommended technique, this function overestimates the
     amount of space required by the size of N-1 cmsghdr structures, where N
     is the number of options to be stored in the object.  This is of little
     consequence, since it is assumed that most Hop-by-Hop option headers and
     Destination option headers carry only one option (appendix B of
     [RFC-2460]).

   inet6_option_init
     inet6_option_init() is called once per ancillary data object that will
     contain either Hop-by-Hop or Destination options.  It returns 0 on suc-
     cess or -1 on an error.

     bp is a pointer to previously allocated space that will contain the
     ancillary data object.  It must be large enough to contain all the indi-
     vidual options to be added by later calls to inet6_option_append() and
     inet6_option_alloc().

     cmsgp is a pointer to a pointer to a cmsghdr structure.  *cmsgp is ini-
     tialized by this function to point to the cmsghdr structure constructed
     by this function in the buffer pointed to by bp.

     type is either IPV6_HOPOPTS or IPV6_DSTOPTS.  This type is stored in the
     cmsg_type member of the cmsghdr structure pointed to by *cmsgp.

   inet6_option_append
     This function appends a Hop-by-Hop option or a Destination option into an
     ancillary data object that has been initialized by inet6_option_init().
     This function returns 0 if it succeeds or -1 on an error.

     cmsg is a pointer to the cmsghdr structure that must have been initial-
     ized by inet6_option_init().

     typep is a pointer to the 8-bit option type.  It is assumed that this
     field is immediately followed by the 8-bit option data length field,
     which is then followed immediately by the option data.  The caller ini-
     tializes these three fields (the type-length-value, or TLV) before call-
     ing this function.

     The option type must have a value from 2 to 255, inclusive.  (0 and 1 are
     reserved for the Pad1 and PadN options, respectively.)

     The option data length must have a value between 0 and 255, inclusive,
     and is the length of the option data that follows.

     multx is the value x in the alignment term ``xn + y''.  It must have a
     value of 1, 2, 4, or 8.

     plusy is the value y in the alignment term ``xn + y''.  It must have a
     value between 0 and 7, inclusive.

   inet6_option_alloc
     This function appends a Hop-by-Hop option or a Destination option into an
     ancillary data object that has been initialized by inet6_option_init().
     This function returns a pointer to the 8-bit option type field that
     starts the option on success, or NULL on an error.

     The difference between this function and inet6_option_append() is that
     the latter copies the contents of a previously built option into the
     ancillary data object while the current function returns a pointer to the
     space in the data object where the option's TLV must then be built by the
     caller.

     cmsg is a pointer to the cmsghdr structure that must have been initial-
     ized by inet6_option_init().

     datalen is the value of the option data length byte for this option.
     This value is required as an argument to allow the function to determine
     if padding must be appended at the end of the option.  (The
     inet6_option_append() function does not need a data length argument since
     the option data length must already be stored by the caller.)

     multx is the value x in the alignment term ``xn + y''.  It must have a
     value of 1, 2, 4, or 8.

     plusy is the value y in the alignment term ``xn + y''.  It must have a
     value between 0 and 7, inclusive.

   inet6_option_next
     This function processes the next Hop-by-Hop option or Destination option
     in an ancillary data object.  If another option remains to be processed,
     the return value of the function is 0 and *tptrp points to the 8-bit
     option type field (which is followed by the 8-bit option data length,
     followed by the option data).  If no more options remain to be processed,
     the return value is -1 and *tptrp is NULL.  If an error occurs, the
     return value is -1 and *tptrp is not NULL.

     cmsg is a pointer to cmsghdr structure of which cmsg_level equals
     IPPROTO_IPV6 and cmsg_type equals either IPV6_HOPOPTS or IPV6_DSTOPTS.

     tptrp is a pointer to a pointer to an 8-bit byte and *tptrp is used by
     the function to remember its place in the ancillary data object each time
     the function is called.  The first time this function is called for a
     given ancillary data object, *tptrp must be set to NULL.

     Each time this function returns success, *tptrp points to the 8-bit
     option type field for the next option to be processed.

   inet6_option_find
     This function is similar to the previously described inet6_option_next()
     function, except this function lets the caller specify the option type to
     be searched for, instead of always returning the next option in the
     ancillary data object.  cmsg is a pointer to cmsghdr structure of which
     cmsg_level equals IPPROTO_IPV6 and cmsg_type equals either IPV6_HOPOPTS
     or IPV6_DSTOPTS.

     tptrp is a pointer to a pointer to an 8-bit byte and *tptrp is used by
     the function to remember its place in the ancillary data object each time
     the function is called.  The first time this function is called for a
     given ancillary data object, *tptrp must be set to NULL.  ~ This function
     starts searching for an option of the specified type beginning after the
     value of *tptrp.  If an option of the specified type is located, this
     function returns 0 and *tptrp points to the 8- bit option type field for
     the option of the specified type.  If an option of the specified type is
     not located, the return value is -1 and *tptrp is NULL.  If an error
     occurs, the return value is -1 and *tptrp is not NULL.

DIAGNOSTICS
     inet6_option_init() and inet6_option_append() return 0 on success or -1
     on an error.

     inet6_option_alloc() returns NULL on an error.

     On errors, inet6_option_next() and inet6_option_find() return -1 setting
     *tptrp to non NULL value.

EXAMPLES
     RFC2292 gives comprehensive examples in chapter 6.

SEE ALSO
     W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC2292,
     February 1998.

     S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6)
     Specification, RFC2460, December 1998.

HISTORY
     The implementation first appeared in KAME advanced networking kit.

STANDARDS
     The functions are documented in ``Advanced Sockets API for IPv6''
     (RFC2292).

BUGS
     The text was shamelessly copied from RFC2292.

BSD                            December 10, 1999                           BSD

143.16. inet6_rthdr_space

INET6_RTHDR_SPACE(3)     BSD Library Functions Manual     INET6_RTHDR_SPACE(3)

NAME
     inet6_rthdr_space, inet6_rthdr_init, inet6_rthdr_add,
     inet6_rthdr_lasthop, inet6_rthdr_reverse, inet6_rthdr_segments,
     inet6_rthdr_getaddr, inet6_rthdr_getflags -- IPv6 Routing Header Options
     manipulation

SYNOPSIS
     #include <netinet/in.h>

     size_t
     inet6_rthdr_space(int type, int segments);

     struct cmsghdr *
     inet6_rthdr_init(void *bp, int type);

     int
     inet6_rthdr_add(struct cmsghdr *cmsg, const struct in6_addr *addr,
         unsigned int flags);

     int
     inet6_rthdr_lasthop(struct cmsghdr *cmsg, unsigned int flags);

     int
     inet6_rthdr_reverse(const struct cmsghdr *in, struct cmsghdr *out);

     int
     inet6_rthdr_segments(const struct cmsghdr *cmsg);

     struct in6_addr *
     inet6_rthdr_getaddr(struct cmsghdr *cmsg, int index);

     int
     inet6_rthdr_getflags(const struct cmsghdr *cmsg, int index);

DESCRIPTION
     RFC2292 IPv6 advanced API defines eight functions that the application
     calls to build and examine a Routing header.  Four functions build a
     Routing header:

     inet6_rthdr_space() return #bytes required for ancillary data

     inet6_rthdr_init() initialize ancillary data for Routing header

     inet6_rthdr_add() add IPv6 address & flags to Routing header

     inet6_rthdr_lasthop() specify the flags for the final hop

     Four functions deal with a returned Routing header:

     inet6_rthdr_reverse() reverse a Routing header

     inet6_rthdr_segments() return #segments in a Routing header

     inet6_rthdr_getaddr() fetch one address from a Routing header

     inet6_rthdr_getflags() fetch one flag from a Routing header

     The function prototypes for these functions are all in the <netinet/in.h>
     header.

   inet6_rthdr_space
     This function returns the number of bytes required to hold a Routing
     header of the specified type containing the specified number of segments
     (addresses).  For an IPv6 Type 0 Routing header, the number of segments
     must be between 1 and 23, inclusive.  The return value includes the size
     of the cmsghdr structure that precedes the Routing header, and any
     required padding.

     If the return value is 0, then either the type of the Routing header is
     not supported by this implementation or the number of segments is invalid
     for this type of Routing header.

     Note: This function returns the size but does not allocate the space
     required for the ancillary data.  This allows an application to allocate
     a larger buffer, if other ancillary data objects are desired, since all
     the ancillary data objects must be specified to sendmsg(2) as a single
     msg_control buffer.

   inet6_rthdr_init
     This function initializes the buffer pointed to by bp to contain a
     cmsghdr structure followed by a Routing header of the specified type.
     The cmsg_len member of the cmsghdr structure is initialized to the size
     of the structure plus the amount of space required by the Routing header.
     The cmsg_level and cmsg_type members are also initialized as required.

     The caller must allocate the buffer and its size can be determined by
     calling inet6_rthdr_space().

     Upon success the return value is the pointer to the cmsghdr structure,
     and this is then used as the first argument to the next two functions.
     Upon an error the return value is NULL.

   inet6_rthdr_add
     This function adds the address pointed to by addr to the end of the Rout-
     ing header being constructed and sets the type of this hop to the value
     of flags.  For an IPv6 Type 0 Routing header, flags must be either
     IPV6_RTHDR_LOOSE or IPV6_RTHDR_STRICT.

     If successful, the cmsg_len member of the cmsghdr structure is updated to
     account for the new address in the Routing header and the return value of
     the function is 0.  Upon an error the return value of the function is -1.

   inet6_rthdr_lasthop
     This function specifies the Strict/Loose flag for the final hop of a
     Routing header.  For an IPv6 Type 0 Routing header, flags must be either
     IPV6_RTHDR_LOOSE or IPV6_RTHDR_STRICT.

     The return value of the function is 0 upon success, or -1 upon an error.

     Notice that a Routing header specifying N intermediate nodes requires N+1
     Strict/Loose flags.  This requires N calls to inet6_rthdr_add() followed
     by one call to inet6_rthdr_lasthop().

   inet6_rthdr_reverse
     This function takes a Routing header that was received as ancillary data
     (pointed to by the first argument, in) and writes a new Routing header
     that sends datagrams along the reverse of that route.  Both arguments are
     allowed to point to the same buffer (that is, the reversal can occur in
     place).

     The return value of the function is 0 on success, or -1 upon an error.

   inet6_rthdr_segments
     This function returns the number of segments (addresses) contained in the
     Routing header described by cmsg.  On success the return value is between
     1 and 23, inclusive.  The return value of the function is -1 upon an
     error.

   inet6_rthdr_getaddr
     This function returns a pointer to the IPv6 address specified by index
     (which must have a value between 1 and the value returned by
     inet6_rthdr_segments()) in the Routing header described by cmsg.  An
     application should first call inet6_rthdr_segments() to obtain the number
     of segments in the Routing header.

     Upon an error the return value of the function is NULL.

   inet6_rthdr_getflags
     This function returns the flags value specified by index (which must have
     a value between 0 and the value returned by inet6_rthdr_segments()) in
     the Routing header described by cmsg.  For an IPv6 Type 0 Routing header
     the return value will be either IPV6_RTHDR_LOOSE or IPV6_RTHDR_STRICT.

     Upon an error the return value of the function is -1.

     Note: Addresses are indexed starting at 1, and flags starting at 0, to
     maintain consistency with the terminology and figures in RFC2460.

DIAGNOSTICS
     inet6_rthdr_space() returns 0 on errors.

     inet6_rthdr_add(), inet6_rthdr_lasthop() and inet6_rthdr_reverse() return
     0 on success, and returns -1 on error.

     inet6_rthdr_init() and inet6_rthdr_getaddr() return NULL on error.

     inet6_rthdr_segments() and inet6_rthdr_getflags() return -1 on error.

EXAMPLES
     RFC2292 gives comprehensive examples in chapter 8.

SEE ALSO
     W. Stevens and M. Thomas, Advanced Sockets API for IPv6, RFC2292,
     February 1998.

     S. Deering and R. Hinden, Internet Protocol, Version 6 (IPv6)
     Specification, RFC2460, December 1998.

HISTORY
     The implementation first appeared in KAME advanced networking kit.

STANDARDS
     The functions are documented in ``Advanced Sockets API for IPv6''
     (RFC2292).

BUGS
     The text was shamelessly copied from RFC2292.

     inet6_rthdr_reverse() is not implemented yet.

BSD                            December 10, 1999                           BSD

143.17. inet_net

INET_NET(3)              BSD Library Functions Manual              INET_NET(3)

NAME
     inet_net_ntop, inet_net_pton -- Internet network number manipulation rou-
     tines

SYNOPSIS
     #include <sys/socket.h>
     #include <netinet/in.h>
     #include <arpa/inet.h>

     char *
     inet_net_ntop(int af, const void *src, int bits, char *dst, size_t size);

     int
     inet_net_pton(int af, const char *src, void *dst, size_t size);

DESCRIPTION
     The inet_net_ntop() function converts an Internet network number from
     network format (usually a struct in_addr or some other binary form, in
     network byte order) to CIDR presentation format (suitable for external
     display purposes).  bits is the number of bits in src that are the net-
     work number.  It returns NULL if a system error occurs (in which case,
     errno will have been set), or it returns a pointer to the destination
     string.

     The inet_net_pton() function converts a presentation format Internet net-
     work number (that is, printable form as held in a character string) to
     network format (usually a struct in_addr or some other internal binary
     representation, in network byte order).  It returns the number of bits
     (either computed based on the class, or specified with /CIDR), or -1 if a
     failure occurred (in which case errno will have been set.  It will be set
     to ENOENT if the Internet network number was not valid).

     The only value for af currently supported is AF_INET.  size is the size
     of the result buffer dst.

NETWORK NUMBERS (IP VERSION 4)
     Internet network numbers may be specified in one of the following forms:

           a.b.c.d/bits
           a.b.c.d
           a.b.c
           a.b
           a

     When four parts are specified, each is interpreted as a byte of data and
     assigned, from left to right, to the four bytes of an Internet network
     number.  Note that when an Internet network number is viewed as a 32-bit
     integer quantity on a system that uses little-endian byte order (such as
     the Intel 386, 486, and Pentium processors) the bytes referred to above
     appear as ``d.c.b.a''.  That is, little-endian bytes are ordered from
     right to left.

     When a three part number is specified, the last part is interpreted as a
     16-bit quantity and placed in the rightmost two bytes of the Internet
     network number.  This makes the three part number format convenient for
     specifying Class B network numbers as ``128.net.host''.

     When a two part number is supplied, the last part is interpreted as a
     24-bit quantity and placed in the rightmost three bytes of the Internet
     network number.  This makes the two part number format convenient for
     specifying Class A network numbers as ``net.host''.

     When only one part is given, the value is stored directly in the Internet
     network number without any byte rearrangement.

     All numbers supplied as ``parts'' in a `.' notation may be decimal,
     octal, or hexadecimal, as specified in the C language (i.e., a leading 0x
     or 0X implies hexadecimal; otherwise, a leading 0 implies octal; other-
     wise, the number is interpreted as decimal).

SEE ALSO
     byteorder(3), inet(3), networks(5)

HISTORY
     The inet_net_ntop and inet_net_pton functions first appeared in BIND
     4.9.4.

BSD                              June 18, 1997                             BSD

143.18. ipx

IPX(3)                   BSD Library Functions Manual                   IPX(3)

NAME
     ipx_addr, ipx_ntoa -- IPX address conversion routines

SYNOPSIS
     #include <sys/types.h>
     #include <netipx/ipx.h>

     struct ipx_addr
     ipx_addr(const char *cp);

     char *
     ipx_ntoa(struct ipx_addr ipx);

DESCRIPTION
     The routine ipx_addr() interprets character strings representing IPX
     addresses, returning binary information suitable for use in system calls.
     The routine ipx_ntoa() takes IPX addresses and returns ASCII strings rep-
     resenting the address in a notation in common use:

           <network number>.<host number>.<port number>

     Trailing zero fields are suppressed, and each number is printed in hexa-
     decimal, in a format suitable for input to ipx_addr().  Any fields lack-
     ing super-decimal digits will have a trailing `H' appended.

     An effort has been made to ensure that ipx_addr() be compatible with most
     formats in common use.  It will first separate an address into 1 to 3
     fields using a single delimiter chosen from period (`.'), colon (`:'), or
     pound-sign (`#').  Each field is then examined for byte separators (colon
     or period).  If there are byte separators, each subfield separated is
     taken to be a small hexadecimal number, and the entirety is taken as a
     network-byte-ordered quantity to be zero extended in the high-network-
     order bytes.  Next, the field is inspected for hyphens, in which case the
     field is assumed to be a number in decimal notation with hyphens separat-
     ing the millenia.  Next, the field is assumed to be a number: It is
     interpreted as hexadecimal if there is a leading `0x' (as in C), a trail-
     ing `H' (as in Mesa), or there are any super-decimal digits present.  It
     is interpreted as octal is there is a leading `0' and there are no super-
     octal digits.  Otherwise, it is converted as a decimal number.

RETURN VALUES
     None.  (See BUGS.)

SEE ALSO
     ns(4), hosts(5), networks(5)

HISTORY
     The precursor ns_addr() and ns_ntoa() functions appeared in 4.3BSD.

BUGS
     The string returned by ipx_ntoa() resides in a static memory area.  The
     function ipx_addr() should diagnose improperly formed input, and there
     should be an unambiguous way to recognize this.

BSD                              June 4, 1993                              BSD

143.19. iso_addr

ISO_ADDR(3)              BSD Library Functions Manual              ISO_ADDR(3)

NAME
     iso_addr, iso_ntoa -- network address conversion routines for Open System
     Interconnection

SYNOPSIS
     #include <sys/types.h>
     #include <netiso/iso.h>

     struct iso_addr *
     iso_addr(char *cp);

     char *
     iso_ntoa(struct iso_addr *isoa);

DESCRIPTION
     The routine iso_addr() interprets character strings representing OSI
     addresses, returning binary information suitable for use in system calls.
     The routine iso_ntoa() takes OSI addresses and returns ASCII strings rep-
     resenting NSAPs (network service access points) in a notation inverse to
     that accepted by iso_addr().

     Unfortunately, no universal standard exists for representing OSI network
     addresses.

     The format employed by iso_addr() is a sequence of hexadecimal ``digits''
     (optionally separated by periods), of the form:

           <hex digits>.<hex digits>.<hex digits>

     Each pair of hexadecimal digits represents a byte with the leading digit
     indicating the higher-ordered bits.  A period following an even number of
     bytes has no effect (but may be used to increase legibility).  A period
     following an odd number of bytes has the effect of causing the byte of
     address being translated to have its higher order bits filled with zeros.

RETURN VALUES
     iso_ntoa() always returns a null terminated string.  iso_addr() always
     returns a pointer to a struct iso_addr.  (See BUGS.)

SEE ALSO
     iso(4)

HISTORY
     The iso_addr() and iso_ntoa() functions appeared in 4.3BSD-Reno.

BUGS
     The returned values reside in a static memory area.

     The function iso_addr() should diagnose improperly formed input, and
     there should be an unambiguous way to recognize this.

BSD                              June 4, 1993                              BSD

143.21. net_addrcmp

NET_ADDRCMP(3)           BSD Library Functions Manual           NET_ADDRCMP(3)

NAME
     net_addrcmp -- compare socket address structures

SYNOPSIS
     #include <netdb.h>

     int
     net_addrcmp(struct sockaddr *sa1, struct sockaddr *sa2);

DESCRIPTION
     The net_addrcmp() function compares two socket address structures, sa1
     and sa2.

RETURN VALUES
     If sa1 and sa2 are for the same address, net_addrcmp() returns 0.

     The sa_len fields are compared first.  If they do not match,
     net_addrcmp() returns -1 or 1 if sa1->sa_len is less than or greater than
     sa2->sa_len, respectively.

     Next, the sa_family members are compared.  If they do not match,
     net_addrcmp() returns -1 or 1 if sa1->sa_family is less than or greater
     than sa2->sa_family, respectively.

     Lastly, if each socket address structure's sa_len and sa_family fields
     match, the protocol-specific data (the sa_data field) is compared.  If
     there's a match, both sa1 and sa2 must refer to the same address, and 0
     is returned; otherwise, a value >0 or <0 is returned.

HISTORY
     A net_addrcmp() function was added in OpenBSD 2.5.

BSD                              July 3, 1999                              BSD

143.22. ns

NS(3)                    BSD Library Functions Manual                    NS(3)

NAME
     ns_addr, ns_ntoa -- Xerox NS(tm) address conversion routines

SYNOPSIS
     #include <sys/types.h>
     #include <netns/ns.h>

     struct ns_addr
     ns_addr(char *cp);

     char *
     ns_ntoa(struct ns_addr ns);

DESCRIPTION
     The routine ns_addr() interprets character strings representing XNS
     addresses, returning binary information suitable for use in system calls.
     The routine ns_ntoa() takes XNS addresses and returns ASCII strings rep-
     resenting the address in a notation in common use in the Xerox Develop-
     ment Environment:

           <network number>.<host number>.<port number>

     Trailing zero fields are suppressed, and each number is printed in hexa-
     decimal, in a format suitable for input to ns_addr().  Any fields lacking
     super-decimal digits will have a trailing `H' appended.

     Unfortunately, no universal standard exists for representing XNS
     addresses.  An effort has been made to ensure that ns_addr() be compati-
     ble with most formats in common use.  It will first separate an address
     into 1 to 3 fields using a single delimiter chosen from period (`.'),
     colon (`:'), or pound-sign `#'.  Each field is then examined for byte
     separators (colon or period).  If there are byte separators, each sub-
     field separated is taken to be a small hexadecimal number, and the
     entirety is taken as a network-byte-ordered quantity to be zero extended
     in the high-network-order bytes.  Next, the field is inspected for
     hyphens, in which case the field is assumed to be a number in decimal
     notation with hyphens separating the millenia.  Next, the field is
     assumed to be a number: It is interpreted as hexadecimal if there is a
     leading `0x' (as in C), a trailing `H' (as in Mesa), or there are any
     super-decimal digits present.  It is interpreted as octal is there is a
     leading `0' and there are no super-octal digits.  Otherwise, it is con-
     verted as a decimal number.

RETURN VALUES
     None.  (See BUGS.)

SEE ALSO
     hosts(5), networks(5)

HISTORY
     The ns_addr() and ns_toa() functions appeared in 4.3BSD.

BUGS
     The string returned by ns_ntoa() resides in a static memory area.  The
     function ns_addr() should diagnose improperly formed input, and there
     should be an unambiguous way to recognize this.

BSD                              June 4, 1993                              BSD

143.23. resolver

RESOLVER(3)              BSD Library Functions Manual              RESOLVER(3)

NAME
     res_query, res_search, res_mkquery, res_send, res_init, dn_comp,
     dn_expand -- resolver routines

SYNOPSIS
     #include <sys/types.h>
     #include <netinet/in.h>
     #include <arpa/nameser.h>
     #include <resolv.h>

     int
     res_query(char *dname, int class, int type, u_char *answer, int anslen);

     int
     res_search(char *dname, int class, int type, u_char *answer, int anslen);

     int
     res_mkquery(int op, char *dname, int class, int type, char *data,
         int datalen, struct rrec *newrr, char *buf, int buflen);

     int
     res_send(char *msg, int msglen, char *answer, int anslen);

     int
     res_init(void);

     int
     dn_comp(char *exp_dn, char *comp_dn, int length, char **dnptrs,
         char **lastdnptr);

     int
     dn_expand(u_char *msg, u_char *eomorig, u_char *comp_dn, u_char *exp_dn,
         int length);

DESCRIPTION
     These routines are used for making, sending, and interpreting query and
     reply messages with Internet domain name servers.

     Global configuration and state information that is used by the resolver
     routines is kept in the structure _res.  Most of the values have reason-
     able defaults and can be ignored.  Options stored in _res.options are
     defined in <resolv.h> and are as follows.  Options are stored as a simple
     bit mask containing the bitwise OR of the options enabled.

     RES_INIT       True if the initial name server address and default domain
                    name are initialized (i.e., res_init() has been called).

     RES_DEBUG      Print debugging messages.

     RES_AAONLY     Accept authoritative answers only.  With this option,
                    res_send() should continue until it finds an authoritative
                    answer or finds an error.  Currently this is not imple-
                    mented.

     RES_USEVC      Use TCP connections for queries instead of UDP datagrams.

     RES_STAYOPEN   Used with RES_USEVC to keep the TCP connection open
                    between queries.  This is useful only in programs that
                    regularly do many queries.  UDP should be the normal mode
                    used.

     RES_IGNTC      Unused currently (ignore truncation errors, i.e., don't
                    retry with TCP).

     RES_RECURSE    Set the recursion-desired bit in queries.  This is the
                    default.  (res_send() does not do iterative queries and
                    expects the name server to handle recursion.)

     RES_DEFNAMES   If set, res_search() will append the default domain name
                    to single-component names (those that do not contain a
                    dot).  This option is enabled by default.

     RES_DNSRCH     If this option is set, res_search() will search for host
                    names in the current domain and in parent domains; see
                    hostname(7).  This is used by the standard host lookup
                    routine gethostbyname(3).  This option is enabled by
                    default.

     RES_USE_INET6  Enables support for IPv6-only applications.  This causes
                    IPv4 addresses to be returned as an IPv4 mapped address.
                    For example, 10.1.1.1 will be returned as ::ffff:10.1.1.1.
                    The option is not meaningful on OpenBSD.

     The res_init() routine reads the configuration file (if any; see
     resolv.conf(5)) to get the default domain name, search list, and the
     Internet address of the local name server(s).  If no server is config-
     ured, the host running the resolver is tried.  The current domain name is
     defined by the hostname if not specified in the configuration file; it
     can be overridden by the environment variable LOCALDOMAIN.  This environ-
     ment variable may contain several blank-separated tokens if you wish to
     override the search list on a per-process basis.  This is similar to the
     search command in the configuration file.  Another environment variable
     RES_OPTIONS can be set to override certain internal resolver options
     which are otherwise set by changing fields in the _res structure or are
     inherited from the configuration file's options command.  The syntax of
     the RES_OPTIONS environment variable is explained in resolv.conf(5).
     Initialization normally occurs on the first call to one of the following
     routines.

     The res_query() function provides an interface to the server query mecha-
     nism.  It constructs a query, sends it to the local server, awaits a
     response, and makes preliminary checks on the reply.  The query requests
     information of the specified type and class for the specified fully qual-
     ified domain name dname.  The reply message is left in the answer buffer
     with length anslen supplied by the caller.

     The res_search() routine makes a query and awaits a response like
     res_query(), but in addition, it implements the default and search rules
     controlled by the RES_DEFNAMES and RES_DNSRCH options.  It returns the
     first successful reply.

     The remaining routines are lower-level routines used by res_query().  The
     res_mkquery() function constructs a standard query message and places it
     in buf.  It returns the size of the query, or -1 if the query is larger
     than buflen.  The query type op is usually QUERY, but can be any of the
     query types defined in <arpa/nameser.h>.  The domain name for the query
     is given by dname.  newrr is currently unused but is intended for making
     update messages.

     The res_send() routine sends a pre-formatted query and returns an answer.
     It will call res_init() if RES_INIT is not set, send the query to the
     local name server, and handle timeouts and retries.  The length of the
     reply message is returned, or -1 if there were errors.

     The dn_comp() function compresses the domain name exp_dn and stores it in
     comp_dn.  The size of the compressed name is returned or -1 if there were
     errors.  The size of the array pointed to by comp_dn is given by length.
     The compression uses an array of pointers dnptrs to previously compressed
     names in the current message.  The first pointer points to the beginning
     of the message and the list ends with NULL.  The limit to the array is
     specified by lastdnptr.  A side effect of dn_comp() is to update the list
     of pointers for labels inserted into the message as the name is com-
     pressed.  If dnptr is NULL, names are not compressed.  If lastdnptr is
     NULL, the list of labels is not updated.

     The dn_expand() entry expands the compressed domain name comp_dn to a
     full domain name The compressed name is contained in a query or reply
     message; msg is a pointer to the beginning of the message.  The uncom-
     pressed name is placed in the buffer indicated by exp_dn which is of size
     length.  The size of compressed name is returned or -1 if there was an
     error.

FILES
     /etc/resolv.conf configuration file see resolv.conf(5).

SEE ALSO
     gethostbyname(3), resolv.conf(5), hostname(7), named(8)

     RFC1032, RFC1033, RFC1034, RFC1035, RFC1535, RFC974

     Name Server Operations Guide for BIND.

HISTORY
     The res_query function appeared in 4.3BSD.

BSD                              June 4, 1993                              BSD

143.24. accept

ACCEPT(2)                   BSD System Calls Manual                  ACCEPT(2)

NAME
     accept -- accept a connection on a socket

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     accept(int s, struct sockaddr *addr, socklen_t *addrlen);

DESCRIPTION
     The argument s is a socket that has been created with socket(2), bound to
     an address with bind(2), and is listening for connections after a
     listen(2).  The accept() argument extracts the first connection request
     on the queue of pending connections, creates a new socket with the same
     properties of s, and allocates a new file descriptor for the socket.  If
     no pending connections are present on the queue, and the socket is not
     marked as non-blocking, accept() blocks the caller until a connection is
     present.  If the socket is marked non-blocking and no pending connections
     are present on the queue, accept() returns an error as described below.
     The accepted socket may not be used to accept more connections.  The
     original socket s remains open.

     The argument addr is a result parameter that is filled in with the
     address of the connecting entity as known to the communications layer.
     The exact format of the addr parameter is determined by the domain in
     which the communication is occurring.  The addrlen is a value-result
     parameter; it should initially contain the amount of space pointed to by
     addr; on return it will contain the actual length (in bytes) of the
     address returned.  This call is used with connection-based socket types,
     currently with SOCK_STREAM.

     It is possible to select(2) or poll(2) a socket for the purposes of doing
     an accept() by selecting it for read.

     For certain protocols which require an explicit confirmation, such as ISO
     or DATAKIT, accept() can be thought of as merely dequeuing the next con-
     nection request and not implying confirmation.  Confirmation can be
     implied by a normal read or write on the new file descriptor, and rejec-
     tion can be implied by closing the new socket.

     One can obtain user connection request data without confirming the con-
     nection by issuing a recvmsg(2) call with an msg_iovlen of 0 and a non-
     zero msg_controllen, or by issuing a getsockopt(2) request.  Similarly,
     one can provide user connection rejection information by issuing a
     sendmsg(2) call with providing only the control information, or by call-
     ing setsockopt(2).

RETURN VALUES
     The call returns -1 on error.  If it succeeds, it returns a non-negative
     integer that is a descriptor for the accepted socket.

ERRORS
     The accept() will fail if:

     [EBADF]            The descriptor is invalid.

     [ENOTSOCK]         The descriptor references a file, not a socket.

     [EOPNOTSUPP]       The referenced socket is not of type SOCK_STREAM.

     [EINVAL]           The referenced socket is not listening for connections
                        (that is, listen(2) has not yet been called).

     [EFAULT]           The addr parameter is not in a writable part of the
                        user address space.

     [EWOULDBLOCK]      The socket is marked non-blocking and no connections
                        are present to be accepted.

     [EMFILE]           The per-process descriptor table is full.

     [ENFILE]           The system file table is full.

     [ECONNABORTED]     A connection has been aborted.

SEE ALSO
     bind(2), connect(2), listen(2), poll(2), select(2), poll(2), socket(2)

HISTORY
     The accept() function appeared in 4.2BSD.

BSD                            February 15, 1999                           BSD

143.25. bind

BIND(2)                     BSD System Calls Manual                    BIND(2)

NAME
     bind -- bind a name to a socket

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     bind(int s, const struct sockaddr *name, socklen_t namelen);

DESCRIPTION
     bind() assigns a name to an unnamed socket.  When a socket is created
     with socket(2) it exists in a name space (address family) but has no name
     assigned.  bind() requests that name be assigned to the socket.

NOTES
     Binding a name in the UNIX domain creates a socket in the file system
     that must be deleted by the caller when it is no longer needed (using
     unlink(2)).

     The rules used in name binding vary between communication domains.  Con-
     sult the manual entries in section 4 for detailed information.

RETURN VALUES
     If the bind is successful, a 0 value is returned.  A return value of -1
     indicates an error, which is further specified in the global errno.

ERRORS
     The bind() call will fail if:

     [EBADF]            S is not a valid descriptor.

     [ENOTSOCK]         S is not a socket.

     [EADDRNOTAVAIL]    The specified address is not available from the local
                        machine.

     [EADDRINUSE]       The specified address is already in use.

     [EINVAL]           The socket is already bound to an address.

     [EINVAL]           The family of the socket and that requested in
                        name->sa_family are not equivalent.

     [EACCES]           The requested address is protected, and the current
                        user has inadequate permission to access it.

     [EFAULT]           The name parameter is not in a valid part of the user
                        address space.

     The following errors are specific to binding names in the UNIX domain.

     [ENOTDIR]          A component of the path prefix is not a directory.

     [ENAMETOOLONG]     A component of a pathname exceeded {NAME_MAX} charac-
                        ters, or an entire path name exceeded {PATH_MAX} char-
                        acters.

     [ENOENT]           A prefix component of the path name does not exist.

     [ELOOP]            Too many symbolic links were encountered in translat-
                        ing the pathname.

     [EIO]              An I/O error occurred while making the directory entry
                        or allocating the inode.

     [EROFS]            The name would reside on a read-only file system.

     [EISDIR]           An empty pathname was specified.

SEE ALSO
     connect(2), getsockname(2), listen(2), socket(2)

HISTORY
     The bind() function call appeared in 4.2BSD.

BSD                            February 15, 1999                           BSD

143.26. connect

CONNECT(2)                  BSD System Calls Manual                 CONNECT(2)

NAME
     connect -- initiate a connection on a socket

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     connect(int s, const struct sockaddr *name, socklen_t namelen);

DESCRIPTION
     The parameter s is a socket.  If it is of type SOCK_DGRAM, this call
     specifies the peer with which the socket is to be associated; this
     address is that to which datagrams are to be sent, and the only address
     from which datagrams are to be received.  If the socket is of type
     SOCK_STREAM, this call attempts to make a connection to another socket.
     The other socket is specified by name, which is an address in the commu-
     nications space of the socket.  Each communications space interprets the
     name parameter in its own way.  Generally, stream sockets may success-
     fully connect() only once; datagram sockets may use connect() multiple
     times to change their association.  Datagram sockets may dissolve the
     association by connecting to an invalid address, such as a null address.

RETURN VALUES
     If the connection or binding succeeds, 0 is returned.  Otherwise a -1 is
     returned, and a more specific error code is stored in errno.

ERRORS
     The connect() call fails if:

     [EBADF]            S is not a valid descriptor.

     [ENOTSOCK]         S is a descriptor for a file, not a socket.

     [EADDRNOTAVAIL]    The specified address is not available on this
                        machine.

     [EAFNOSUPPORT]     Addresses in the specified address family cannot be
                        used with this socket.

     [EISCONN]          The socket is already connected.

     [ETIMEDOUT]        Connection establishment timed out without establish-
                        ing a connection.

     [EINVAL]           A TCP connection with a local broadcast, the all-ones
                        or a multicast address as the peer was attempted.

     [ECONNREFUSED]     The attempt to connect was forcefully rejected.

     [EINTR]            A connect was interrupted before it succeeded by the
                        delivery of a signal.

     [ENETUNREACH]      The network isn't reachable from this host.

     [EADDRINUSE]       The address is already in use.

     [EFAULT]           The name parameter specifies an area outside the
                        process address space.

     [EINPROGRESS]      The socket is non-blocking and the connection cannot
                        be completed immediately.  It is possible to select(2)
                        or poll(2) for completion by selecting the socket for
                        writing, and also use getsockopt(2) with SO_ERROR to
                        check for error conditions.

     [EALREADY]         The socket is non-blocking and a previous connection
                        attempt has not yet been completed.

     The following errors are specific to connecting names in the UNIX domain.
     These errors may not apply in future versions of the UNIX IPC domain.

     [ENOTDIR]          A component of the path prefix is not a directory.

     [ENAMETOOLONG]     A component of a pathname exceeded {NAME_MAX} charac-
                        ters, or an entire path name exceeded {PATH_MAX} char-
                        acters.

     [ENOENT]           The named socket does not exist.

     [EACCES]           Search permission is denied for a component of the
                        path prefix.

     [EACCES]           Write access to the named socket is denied.

     [ELOOP]            Too many symbolic links were encountered in translat-
                        ing the pathname.

SEE ALSO
     accept(2), getsockname(2), getsockopt(2), poll(2), select(2), socket(2)

HISTORY
     The connect() function call appeared in 4.2BSD.

BSD                            February 15, 1999                           BSD

143.27. getpeername

GETPEERNAME(2)              BSD System Calls Manual             GETPEERNAME(2)

NAME
     getpeername -- get name of connected peer

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     getpeername(int s, struct sockaddr *name, socklen_t *namelen);

DESCRIPTION
     getpeername() returns the address information of the peer connected to
     socket s.  One common use occurs when a process inherits an open socket,
     such as TCP servers forked from inetd(8).  In this scenario,
     getpeername() is used to determine the connecting client's IP address.

     getpeername() takes three parameters:

     s Contains the file descriptor of the socket whose peer should be looked
     up.

     name Points to a sockaddr structure that will hold the address informa-
     tion for the connected peer.  Normal use requires one to use a structure
     specific to the protocol family in use, such as sockaddr_in (IPv4) or
     sockaddr_in6 (IPv6), cast to a (struct sockaddr *).

     For greater portability, especially with the newer protocol families, the
     new struct sockaddr_storage should be used.  sockaddr_storage is large
     enough to hold any of the other sockaddr_* variants.  On return, it can
     be cast to the correct sockaddr type, based the protocol family contained
     in its ss_family field.

     namelen Indicates the amount of space pointed to by name, in bytes.

     If address information for the local end of the socket is required, the
     getsockname(2) function should be used instead.

     If name does not point to enough space to hold the entire socket address,
     the result will be truncated to namelen bytes.

RETURN VALUES
     If the call succeeds, a 0 is returned and namelen is set to the actual
     size of the socket address returned in name.  Otherwise, errno is set and
     a value of -1 is returned.

ERRORS
     On failure, errno is set to one of the following:

     [EBADF]            The argument s is not a valid descriptor.

     [ENOTSOCK]         The argument s is a file, not a socket.

     [ENOTCONN]         The socket is not connected.

     [ENOBUFS]          Insufficient resources were available in the system to
                        perform the operation.

     [EFAULT]           The name parameter points to memory not in a valid
                        part of the process address space.

SEE ALSO
     accept(2), bind(2), getsockname(2), getpeereid(2), socket(2)

HISTORY
     The getpeername() function call appeared in 4.2BSD.

BSD                              July 17, 1999                             BSD

143.28. getsockname

GETSOCKNAME(2)              BSD System Calls Manual             GETSOCKNAME(2)

NAME
     getsockname -- get socket name

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     getsockname(int s, struct sockaddr *name, socklen_t *namelen);

DESCRIPTION
     getsockname() returns the locally bound address information for a speci-
     fied socket.

     Common uses of this function are as follows:

     +   When bind(2) is called with a port number of 0 (indicating the kernel
         should pick an ephemeral port) getsockname() is used to retrieve the
         kernel-assigned port number.

     +   When a process calls bind(2) on a wildcard IP address, getsockname()
         is used to retrieve the local IP address for the connection.

     +   When a function wishes to know the address family of a socket,
         getsockname() can be used.

     getsockname() takes three parameters:

     s, Contains the file desriptor for the socket to be looked up.

     name points to a sockaddr structure which will hold the resulting address
     information.  Normal use requires one to use a structure specific to the
     protocol family in use, such as sockaddr_in (IPv4) or sockaddr_in6
     (IPv6), cast to a (struct sockaddr *).

     For greater portability (such as newer protocol families) the new struc-
     ture sockaddr_storage exists.  sockaddr_storage is large enough to hold
     any of the other sockaddr_* variants.  On return, it should be cast to
     the correct sockaddr type, according to the current protocol family.

     namelen Indicates the amount of space pointed to by name, in bytes.  Upon
     return, namelen is set to the actual size of the returned address infor-
     mation.

     If the address of the destination socket for a given socket connection is
     needed, the getpeername(2) function should be used instead.

     If name does not point to enough space to hold the entire socket address,
     the result will be truncated to namelen bytes.

RETURN VALUES
     On success, getsockname() returns a 0, and namelen is set to the actual
     size of the socket address returned in name.  Otherwise, errno is set,
     and a value of -1 is returned.

ERRORS
     If getsockname() fails, errno is set to one of the following:

     [EBADF]            The argument s is not a valid descriptor.

     [ENOTSOCK]         The argument s is a file, not a socket.

     [ENOBUFS]          Insufficient resources were available in the system to
                        perform the operation.

     [EFAULT]           The name parameter points to memory not in a valid
                        part of the process address space.

SEE ALSO
     accept(2), bind(2), getpeername(2), getpeereid(2), socket(2)

BUGS
     Names bound to sockets in the UNIX domain are inaccessible; getsockname
     returns a zero length name.

HISTORY
     The getsockname() function call appeared in 4.2BSD.

BSD                              July 17, 1999                             BSD

143.29. getsockopt

GETSOCKOPT(2)               BSD System Calls Manual              GETSOCKOPT(2)

NAME
     getsockopt, setsockopt -- get and set options on sockets

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     getsockopt(int s, int level, int optname, void *optval,
         socklen_t *optlen);

     int
     setsockopt(int s, int level, int optname, const void *optval,
         socklen_t optlen);

DESCRIPTION
     getsockopt() and setsockopt() manipulate the options associated with a
     socket.  Options may exist at multiple protocol levels; they are always
     present at the uppermost ``socket'' level.

     When manipulating socket options the level at which the option resides
     and the name of the option must be specified.  To manipulate options at
     the socket level, level is specified as SOL_SOCKET.  To manipulate
     options at any other level the protocol number of the appropriate proto-
     col controlling the option is supplied.  For example, to indicate that an
     option is to be interpreted by the TCP protocol, level should be set to
     the protocol number of TCP; see getprotoent(3).

     The parameters optval and optlen are used to access option values for
     setsockopt().  For getsockopt() they identify a buffer in which the value
     for the requested option(s) are to be returned.  For getsockopt(), optlen
     is a value-result parameter, initially containing the size of the buffer
     pointed to by optval, and modified on return to indicate the actual size
     of the value returned.  If no option value is to be supplied or returned,
     optval may be NULL.

     optname and any specified options are passed uninterpreted to the appro-
     priate protocol module for interpretation.  The include file
     <sys/socket.h> contains definitions for socket level options, described
     below.  Options at other protocol levels vary in format and name; consult
     the appropriate entries in section 4 of the manual.

     Most socket-level options utilize an int parameter for optval.  For
     setsockopt(), the parameter should be non-zero to enable a boolean
     option, or zero if the option is to be disabled.  SO_LINGER uses a struct
     linger parameter, defined in <sys/socket.h>, which specifies the desired
     state of the option and the linger interval (see below).  SO_SNDTIMEO and
     SO_RCVTIMEO use a struct timeval parameter, defined in <sys/time.h>.

     The following options are recognized at the socket level.  Except as
     noted, each may be examined with getsockopt() and set with setsockopt().

           SO_DEBUG        enables recording of debugging information
           SO_REUSEADDR    enables local address reuse
           SO_REUSEPORT    enables duplicate address and port bindings
           SO_KEEPALIVE    enables keep connections alive
           SO_DONTROUTE    enables routing bypass for outgoing messages
           SO_LINGER       linger on close if data present
           SO_BROADCAST    enables permission to transmit broadcast messages
           SO_OOBINLINE    enables reception of out-of-band data in band
           SO_SNDBUF       set buffer size for output
           SO_RCVBUF       set buffer size for input
           SO_SNDLOWAT     set minimum count for output
           SO_RCVLOWAT     set minimum count for input
           SO_SNDTIMEO     set timeout value for output
           SO_RCVTIMEO     set timeout value for input
           SO_TYPE         get the type of the socket (get only)
           SO_ERROR        get and clear error on the socket (get only)

     SO_DEBUG enables debugging in the underlying protocol modules.
     SO_REUSEADDR indicates that the rules used in validating addresses sup-
     plied in a bind(2) call should allow reuse of local addresses.
     SO_REUSEPORT allows completely duplicate bindings by multiple processes
     if they all set SO_REUSEPORT before binding the port.  This option per-
     mits multiple instances of a program to each receive UDP/IP multicast or
     broadcast datagrams destined for the bound port.  SO_KEEPALIVE enables
     the periodic transmission of messages on a connected socket.  Should the
     connected party fail to respond to these messages, the connection is con-
     sidered broken and processes using the socket are notified via a SIGPIPE
     signal when attempting to send data.  SO_DONTROUTE indicates that outgo-
     ing messages should bypass the standard routing facilities.  Instead,
     messages are directed to the appropriate network interface according to
     the network portion of the destination address.

     SO_LINGER controls the action taken when unsent messages are queued on
     socket and a close(2) is performed.  If the socket promises reliable
     delivery of data and SO_LINGER is set, the system will block the process
     on the close(2) attempt until it is able to transmit the data or until it
     decides it is unable to deliver the information (a timeout period mea-
     sured in seconds, termed the linger interval, is specified in the
     setsockopt() call when SO_LINGER is requested).  If SO_LINGER is disabled
     and a close(2) is issued, the system will process the close in a manner
     that allows the process to continue as quickly as possible.

     The option SO_BROADCAST requests permission to send broadcast datagrams
     on the socket.  Broadcast was a privileged operation in earlier versions
     of the system.  With protocols that support out-of-band data, the
     SO_OOBINLINE option requests that out-of-band data be placed in the nor-
     mal data input queue as received; it will then be accessible with recv(2)
     or read(2) calls without the MSG_OOB flag.  Some protocols always behave
     as if this option is set.  SO_SNDBUF and SO_RCVBUF are options to adjust
     the normal buffer sizes allocated for output and input buffers, respec-
     tively.  The buffer size may be increased for high-volume connections, or
     may be decreased to limit the possible backlog of incoming data.  The
     system places an absolute limit on these values.

     SO_SNDLOWAT is an option to set the minimum count for output operations.
     Most output operations process all of the data supplied by the call,
     delivering data to the protocol for transmission and blocking as neces-
     sary for flow control.  Nonblocking output operations will process as
     much data as permitted subject to flow control without blocking, but will
     process no data if flow control does not allow the smaller of the low
     water mark value or the entire request to be processed.  A select(2) or
     poll(2) operation testing the ability to write to a socket will return
     true only if the low water mark amount could be processed.  The default
     value for SO_SNDLOWAT is set to a convenient size for network efficiency,
     often 1024.  SO_RCVLOWAT is an option to set the minimum count for input
     operations.  In general, receive calls will block until any (non-zero)
     amount of data is received, then return with the smaller of the amount
     available or the amount requested.  The default value for SO_RCVLOWAT is
     1.  If SO_RCVLOWAT is set to a larger value, blocking receive calls nor-
     mally wait until they have received the smaller of the low water mark
     value or the requested amount.  Receive calls may still return less than
     the low water mark if an error occurs, a signal is caught, or the type of
     data next in the receive queue is different than that returned.

     SO_SNDTIMEO is an option to set a timeout value for output operations.
     It accepts a struct timeval parameter with the number of seconds and
     microseconds used to limit waits for output operations to complete.  If a
     send operation has blocked for this much time, it returns with a partial
     count or with the error EWOULDBLOCK if no data was sent.  In the current
     implementation, this timer is restarted each time additional data are
     delivered to the protocol, implying that the limit applies to output por-
     tions ranging in size from the low water mark to the high water mark for
     output.  SO_RCVTIMEO is an option to set a timeout value for input opera-
     tions.  It accepts a struct timeval parameter with the number of seconds
     and microseconds used to limit waits for input operations to complete.
     In the current implementation, this timer is restarted each time addi-
     tional data are received by the protocol, and thus the limit is in effect
     an inactivity timer.  If a receive operation has been blocked for this
     much time without receiving additional data, it returns with a short
     count or with the error EWOULDBLOCK if no data were received.

     Finally, SO_TYPE and SO_ERROR are options used only with getsockopt().
     SO_TYPE returns the type of the socket, such as SOCK_STREAM; it is useful
     for servers that inherit sockets on startup.  SO_ERROR returns any pend-
     ing error on the socket and clears the error status.  It may be used to
     check for asynchronous errors on connected datagram sockets or for other
     asynchronous errors.

RETURN VALUES
     A 0 is returned if the call succeeds, -1 if it fails.

ERRORS
     The call succeeds unless:

     [EBADF]            The argument s is not a valid descriptor.

     [ENOTSOCK]         The argument s is a file, not a socket.

     [ENOPROTOOPT]      The option is unknown at the level indicated.

     [EFAULT]           The address pointed to by optval is not in a valid
                        part of the process address space.  For getsockopt(),
                        this error may also be returned if optlen is not in a
                        valid part of the process address space.

SEE ALSO
     connect(2), ioctl(2), poll(2), select(2), poll(2), socket(2),
     getprotoent(3), protocols(5)

BUGS
     Several of the socket options should be handled at lower levels of the
     system.

HISTORY
     The getsockopt() system call appeared in 4.2BSD.

BSD                            February 15, 1999                           BSD

143.30. ioctl

IOCTL(2)                    BSD System Calls Manual                   IOCTL(2)

NAME
     ioctl -- control device

SYNOPSIS
     #include <sys/ioctl.h>

     int
     ioctl(int d, unsigned long request, …);

DESCRIPTION
     The ioctl() function manipulates the underlying device parameters of spe-
     cial files.  In particular, many operating characteristics of character
     special files (e.g., terminals) may be controlled with ioctl() requests.

     The argument d must be an open file descriptor. The third argument is
     called arg and contains additional information needed by this device to
     perform the requested function.  arg is either an int or a pointer to a
     device-specific data structure, depending upon the given request.

     An ioctl request has encoded in it whether the argument is an ``in''
     parameter or ``out'' parameter, and the size of the third argument (arg)
     in bytes.  Macros and defines used in specifying an ioctl request are
     located in the file <sys/ioctl.h>.

RETURN VALUES
     If an error has occurred, a value of -1 is returned and errno is set to
     indicate the error.

ERRORS
     ioctl() will fail if:

     [EBADF]            d is not a valid descriptor.

     [ENOTTY]           d is not associated with a character special device.

     [ENOTTY]           The specified request does not apply to the kind of
                        object that the descriptor d references.

     [EINVAL]           request or arg is not valid.

     [EFAULT]           arg points outside the process's allocated address
                        space.

SEE ALSO
     cdio(1), chio(1), mt(1), execve(2), fcntl(2), intro(4), tty(4)

HISTORY
     An ioctl() function call appeared in Version 7 AT&T UNIX.

BSD                            December 11, 1993                           BSD

143.31. listen

LISTEN(2)                   BSD System Calls Manual                  LISTEN(2)

NAME
     listen -- listen for connections on a socket

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     listen(int s, int backlog);

DESCRIPTION
     To accept connections, a socket is first created with socket(2), a will-
     ingness to accept incoming connections and a queue limit for incoming
     connections are specified with listen(), and then the connections are
     accepted with accept(2).  The listen() call applies only to sockets of
     type SOCK_STREAM or SOCK_SEQPACKET.

     The backlog parameter defines the maximum length the queue of pending
     connections may grow to.  If a connection request arrives with the queue
     full the client may receive an error with an indication of ECONNREFUSED,
     or, if the underlying protocol supports retransmission, the request may
     be ignored so that retries may succeed.

RETURN VALUES
     A 0 return value indicates success; -1 indicates an error.

ERRORS
     listen() will fail if:

     [EBADF]            The argument s is not a valid descriptor.

     [ENOTSOCK]         The argument s is not a socket.

     [EOPNOTSUPP]       The socket is not of a type that supports the opera-
                        tion listen().

SEE ALSO
     accept(2), connect(2), socket(2)

HISTORY
     The listen() function call appeared in 4.2BSD.

BUGS
     The backlog is currently limited (silently) to 128.

BSD                            December 11, 1993                           BSD

143.32. poll

POLL(2)                     BSD System Calls Manual                    POLL(2)

NAME
     poll -- synchronous I/O multiplexing

SYNOPSIS
     #include <poll.h>

     int
     poll(struct pollfd *fds, int nfds, int timeout);

DESCRIPTION
     poll() provides a mechanism for reporting I/O conditions across a set of
     file descriptors.

     The arguments are as follows:

     fds      Points to an array of pollfd structures, which are defined as:

                    struct pollfd {
                            int fd;
                            short events;
                            short revents;
                    };

              The fd member is an open file descriptor.  The events and
              revents members are bitmasks of conditions to monitor and condi-
              tions found, respectively.

     nfds     The number of pollfd structures in the array.

     timeout  Maximum interval to wait for the poll to complete, in millisec-
              onds.  If this value is 0, then poll() will return immediately.
              If this value is INFTIM (-1), poll() will block indefinitely
              until a condition is found.

     The calling process sets the events bitmask and poll() sets the revents
     bitmask.  Each call to poll() resets the revents bitmask for accuracy.
     The condition flags in the bitmasks are defined as:

     POLLIN      Data is available on the file descriptor for reading.

     POLLNORM    Same as POLLIN.

     POLLPRI     Same as POLLIN.

     POLLOUT     Data can be written to the file descriptor without blocking.

     POLLERR     This flag is not used in this implementation and is provided
                 only for source code compatibility.

     POLLHUP     The file descriptor was valid before the polling process and
                 invalid after.  Presumably, this means that the file descrip-
                 tor was closed sometime during the poll.

     POLLNVAL    The corresponding file descriptor is invalid.

     POLLRDNORM  Same as POLLIN.

     POLLRDBAND  Same as POLLIN.

     POLLWRNORM  Same as POLLOUT.

     POLLWRBAND  Same as POLLOUT.

     POLLMSG     This flag is not used in this implementation and is provided
                 only for source code compatibility.

     All flags except POLLIN, POLLOUT, and their synonyms are for use only in
     the revents member of the pollfd structure.  An attempt to set any of
     these flags in the events member will generate an error condition.

     In addition to I/O multiplexing, poll() can be used to generate simple
     timeouts.  This functionality may be achieved by passing a null pointer
     for fds.

WARNINGS
     The POLLHUP flag is only a close approximation and may not always be
     accurate.

RETURN VALUES
     Upon error, poll() returns a -1 and sets the global variable errno to
     indicate the error.  If the timeout interval was reached before any
     events occurred, a 0 is returned.  Otherwise, poll() returns the number
     of file descriptors for which revents is non-zero.

ERRORS
     poll() will fail if:

     [EINVAL]   nfds was either a negative number or greater than the number
                of available file descriptors.

     [EINVAL]   An invalid flags was set in the events member of the pollfd
                structure.

     [EINVAL]   The timeout passed to poll() was too large.

     [EAGAIN]   Resource allocation failed inside of poll().  Subsequent calls
                to poll() may succeed.

     [EINTR]    poll() caught a signal during the polling process.

SEE ALSO
     poll(2), select(2), sysconf(3)

HISTORY
     A poll() system call appeared in AT&T System V UNIX.

BSD                            December 13, 1994                           BSD

143.33. select

SELECT(2)                   BSD System Calls Manual                  SELECT(2)

NAME
     select -- synchronous I/O multiplexing

SYNOPSIS
     #include <sys/types.h>
     #include <sys/time.h>
     #include <unistd.h>

     int
     select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
         struct timeval *timeout);

     FD_SET(fd, &fdset);

     FD_CLR(fd, &fdset);

     FD_ISSET(fd, &fdset);

     FD_ZERO(&fdset);

DESCRIPTION
     select() examines the I/O descriptor sets whose addresses are passed in
     readfds, writefds, and exceptfds to see if some of their descriptors are
     ready for reading, are ready for writing, or have an exceptional condi-
     tion pending, respectively.  The first nfds descriptors are checked in
     each set; i.e., the descriptors from 0 through nfds-1 in the descriptor
     sets are examined.  On return, select() replaces the given descriptor
     sets with subsets consisting of those descriptors that are ready for the
     requested operation.  select() returns the total number of ready descrip-
     tors in all the sets.

     The descriptor sets are stored as bit fields in arrays of integers.  The
     following macros are provided for manipulating such descriptor sets:
     FD_ZERO(&fdset) initializes a descriptor set fdset to the null set.
     FD_SET(fd, &fdset) includes a particular descriptor fd in fdset.
     FD_CLR(fd, &fdset) removes fd from fdset.  FD_ISSET(fd, &fdset) is non-
     zero if fd is a member of fdset, zero otherwise.  The behavior of these
     macros is undefined if a descriptor value is less than zero or greater
     than or equal to FD_SETSIZE, which is normally at least equal to the max-
     imum number of descriptors supported by the system.

     If timeout is a non-null pointer, it specifies a maximum interval to wait
     for the selection to complete.  If timeout is a null pointer, the select
     blocks indefinitely.  To effect a poll, the timeout argument should be
     non-null, pointing to a zero-valued timeval structure.  timeout is not
     changed by select(), and may be reused on subsequent calls; however, it
     is good style to re-initialize it before each invocation of select().

     Any of readfds, writefds, and exceptfds may be given as null pointers if
     no descriptors are of interest.

RETURN VALUES
     select() returns the number of ready descriptors that are contained in
     the descriptor sets, or -1 is an error occurred.  If the time limit
     expires, select() returns 0.  If select() returns with an error, includ-
     ing one due to an interrupted call, the descriptor sets will be unmodi-
     fied.

ERRORS
     An error return from select() indicates:

     [EFAULT]           One or more of readfds, writefds, or exceptfds points
                        outside the process's allocated address space.

     [EBADF]            One of the descriptor sets specified an invalid
                        descriptor.

     [EINTR]            A signal was delivered before the time limit expired
                        and before any of the selected events occurred.

     [EINVAL]           The specified time limit is invalid.  One of its com-
                        ponents is negative or too large.

SEE ALSO
     accept(2), connect(2), gettimeofday(2), poll(2), read(2), recv(2),
     send(2), write(2), getdtablesize(3)

BUGS
     Although the provision of getdtablesize(3) was intended to allow user
     programs to be written independent of the kernel limit on the number of
     open files, the dimension of a sufficiently large bit field for select
     remains a problem.  The default bit size of fd_set is based on the symbol
     FD_SETSIZE (currently 256), but that is somewhat smaller than the current
     kernel limit to the number of open files.  However, in order to accommo-
     date programs which might potentially use a larger number of open files
     with select, it is possible to increase this size within a program by
     providing a larger definition of FD_SETSIZE before the inclusion of
     <sys/types.h>.  The kernel will cope, and the userland libraries provided
     with the system are also ready for large numbers of file descriptors.

     Alternatively, to be really safe, it is possible to allocate fd_set bit-
     arrays dynamically.  The idea is to permit a program to work properly
     even if it is execve(2)'d with 4000 file descriptors pre-allocated.  The
     following illustrates the technique which is used by userland libraries:

                   fd_set *fdsr;
                   int max = fd;

                   fdsr = (fd_set *)calloc(howmany(max+1, NFDBITS),
                       sizeof(fd_mask));
                   if (fdsr == NULL) {
                           …
                           return (-1);
                   }
                   FD_SET(fd, fdsr);
                   n = select(max+1, fdsr, NULL, NULL, &tv);
                   …
                   free(fdsr);

     Alternatively, it is possible to use the poll(2) interface.  poll(2) is
     more efficient when the size of select()'s fd_set bit-arrays are very
     large, and for fixed numbers of file descriptors one need not size and
     dynamically allocate a memory object.

     select() should probably have been designed to return the time remaining
     from the original timeout, if any, by modifying the time value in place.
     Even though some systems stupidly act in this different way, it is
     unlikely this semantic will ever be commonly implemented, as the change
     causes massive source code compatibility problems.  Furthermore, recent
     new standards have dictated the current behaviour.  In general, due to
     the existence of those brain-damaged non-conforming systems, it is unwise
     to assume that the timeout value will be unmodified by the select() call,
     and the caller should reinitialize it on each invocation.  Calculating
     the delta is easily done by calling gettimeofday(2) before and after the
     call to select(), and using timersub() (as described in getitimer(2)).

     Internally to the kernel, select() works poorly if multiple processes
     wait on the same file descriptor.  Given that, it is rather surprising to
     see that many daemons are written that way (i.e., httpd(8)).

HISTORY
     The select() function call appeared in 4.2BSD.

BSD                             March 25, 1994                             BSD

143.34. send

SEND(2)                     BSD System Calls Manual                    SEND(2)

NAME
     send, sendto, sendmsg -- send a message from a socket

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     ssize_t
     send(int s, const void *msg, size_t len, int flags);

     ssize_t
     sendto(int s, const void *msg, size_t len, int flags,
         const struct sockaddr *to, socklen_t tolen);

     ssize_t
     sendmsg(int s, const struct msghdr *msg, int flags);

DESCRIPTION
     send(), sendto(), and sendmsg() are used to transmit a message to another
     socket.  send() may be used only when the socket is in a connected state,
     while sendto() and sendmsg() may be used at any time.

     The address of the target is given by to with tolen specifying its size.
     The length of the message is given by len.  If the message is too long to
     pass atomically through the underlying protocol, the error EMSGSIZE is
     returned, and the message is not transmitted.

     No indication of failure to deliver is implicit in a send().  Locally
     detected errors are indicated by a return value of -1.

     If no messages space is available at the socket to hold the message to be
     transmitted, then send() normally blocks, unless the socket has been
     placed in non-blocking I/O mode.  The select(2) or poll(2) system calls
     may be used to determine when it is possible to send more data.

     The flags parameter may include one or more of the following:

     #define MSG_OOB        0x1  /* process out-of-band data */
     #define MSG_DONTROUTE  0x4  /* bypass routing, use direct interface */

     The flag MSG_OOB is used to send ``out-of-band'' data on sockets that
     support this notion (e.g., SOCK_STREAM); the underlying protocol must
     also support ``out-of-band'' data.  MSG_DONTROUTE is usually used only by
     diagnostic or routing programs.

     See recv(2) for a description of the msghdr structure.

RETURN VALUES
     The call returns the number of characters sent, or -1 if an error
     occurred.

ERRORS
     send(), sendto(), and sendmsg() fail if:

     [EBADF]            An invalid descriptor was specified.

     [ENOTSOCK]         The argument s is not a socket.

     [EFAULT]           An invalid user space address was specified for a
                        parameter.

     [EMSGSIZE]         The socket requires that message be sent atomically,
                        and the size of the message to be sent made this
                        impossible.

     [EAGAIN]           The socket is marked non-blocking and the requested
                        operation would block.

     [ENOBUFS]          The system was unable to allocate an internal buffer.
                        The operation may succeed when buffers become avail-
                        able.

     [ENOBUFS]          The output queue for a network interface was full.
                        This generally indicates that the interface has
                        stopped sending, but may be caused by transient con-
                        gestion.

     [EACCES]           The SO_BROADCAST option is not set on the socket, and
                        a broadcast address was given as the destination.

     [EHOSTUNREACH]     The destination address specified an unreachable host.

     [EINVAL]           The flags parameter is invalid.

     [EHOSTDOWN]        The destination address specified a host that is down.

     [ENETDOWN]         The destination address specified a network that is
                        down.

     [ECONNREFUSED]     The destination host rejected the message (or a previ-
                        ous one).  This error can only be returned by con-
                        nected sockets.

     [ENOPROTOOPT]      There was a problem sending the message.  This error
                        can only be returned by connected sockets.

     [EDESTADDRREQ]     The socket is not connected, and no destination
                        address was specified.

     [EISCONN]          The socket is already connected, and a destination
                        address was specified.

     In addition, send() and sendto() may return the following error:

     [EINVAL]           len was larger than SSIZE_MAX.

     Also, sendmsg() may return the following errors:

     [EINVAL]           The sum of the iov_len values in the msg_iov array
                        overflowed an ssize_t.

     [EMSGSIZE]         The msg_iovlen member of msg was less than 0 or larger
                        than IOV_MAX.

     [EAFNOSUPPORT]     Addresses in the specified address family cannot be
                        used with this socket.

SEE ALSO
     fcntl(2), getsockopt(2), poll(2), recv(2), select(2), poll(2), socket(2),
     write(2)

HISTORY
     The send() function call appeared in 4.2BSD.

BSD                              July 28, 1998                             BSD

143.35. shutdown

SHUTDOWN(2)                 BSD System Calls Manual                SHUTDOWN(2)

NAME
     shutdown -- shut down part of a full-duplex connection

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     shutdown(int s, int how);

DESCRIPTION
     The shutdown() call causes all or part of a full-duplex connection on the
     socket associated with s to be shut down.  If how is SHUT_RD, further
     receives will be disallowed.  If how is SHUT_WR, further sends will be
     disallowed.  If how is SHUT_RDWR, further sends and receives will be dis-
     allowed.

RETURN VALUES
     A 0 is returned if the call succeeds, -1 if it fails.

ERRORS
     The call succeeds unless:

     [EINVAL]           how is not SHUT_RD, SHUT_WR, or SHUT_RDWR.

     [EBADF]            s is not a valid descriptor.

     [ENOTSOCK]         s is a file, not a socket.

     [ENOTCONN]         The specified socket is not connected.

SEE ALSO
     connect(2), socket(2)

HISTORY
     The shutdown() function call appeared in 4.2BSD.  The how arguments used
     to be simply 0, 1, and 2, but now have named values as specified by
     X/Open Portability Guide Issue 4 (``XPG4'').

BSD                              June 4, 1993                              BSD

143.36. socket

SOCKET(2)                   BSD System Calls Manual                  SOCKET(2)

NAME
     socket -- create an endpoint for communication

SYNOPSIS
     #include <sys/types.h>
     #include <sys/socket.h>

     int
     socket(int domain, int type, int protocol);

DESCRIPTION
     socket() creates an endpoint for communication and returns a descriptor.

     The domain parameter specifies a communications domain within which com-
     munication will take place; this selects the protocol family which should
     be used.  These families are defined in the include file <sys/socket.h>.
     The currently understood formats are

           AF_UNIX         (UNIX internal protocols),
           AF_INET         (ARPA Internet protocols),
           AF_INET6        (ARPA IPv6 protocols),
           AF_ISO          (ISO protocols),
           AF_NS           (Xerox Network Systems protocols),
           AF_IPX          (Internetwork Packet Exchange), and
           AF_IMPLINK      (IMP host at IMP link layer).

     The socket has the indicated type, which specifies the semantics of com-
     munication.  Currently defined types are:

           SOCK_STREAM
           SOCK_DGRAM
           SOCK_RAW
           SOCK_SEQPACKET
           SOCK_RDM

     A SOCK_STREAM type provides sequenced, reliable, two-way connection based
     byte streams.  An out-of-band data transmission mechanism may be sup-
     ported.  A SOCK_DGRAM socket supports datagrams (connectionless, unreli-
     able messages of a fixed (typically small) maximum length).  A
     SOCK_SEQPACKET socket may provide a sequenced, reliable, two-way connec-
     tion-based data transmission path for datagrams of fixed maximum length;
     a consumer may be required to read an entire packet with each read system
     call.  This facility is protocol specific, and presently implemented only
     for PF_NS.  SOCK_RAW sockets provide access to internal network protocols
     and interfaces.  The types SOCK_RAW, which is available only to the supe-
     ruser, and SOCK_RDM, which is planned, but not yet implemented, are not
     described here.

     The protocol specifies a particular protocol to be used with the socket.
     Normally only a single protocol exists to support a particular socket
     type within a given protocol family.  However, it is possible that many
     protocols may exist, in which case a particular protocol must be speci-
     fied in this manner.  The protocol number to use is particular to the
     communication domain in which communication is to take place; see
     protocols(5).  A value of 0 for protocol will let the system select an
     appropriate protocol for the requested socket type.

     Sockets of type SOCK_STREAM are full-duplex byte streams, similar to
     pipes.  A stream socket must be in a connected state before any data may
     be sent or received on it.  A connection to another socket is created
     with a connect(2) call.  Once connected, data may be transferred using
     read(2) and write(2) calls or some variant of the send(2) and recv(2)
     calls.  When a session has been completed a close(2) may be performed.
     Out-of-band data may also be transmitted as described in send(2) and
     received as described in recv(2).

     The communications protocols used to implement a SOCK_STREAM ensure that
     data is not lost or duplicated.  If a piece of data for which the peer
     protocol has buffer space cannot be successfully transmitted within a
     reasonable length of time, then the connection is considered broken and
     calls will indicate an error with -1 returns and with ETIMEDOUT as the
     specific code in the global variable errno.  The protocols optionally
     keep sockets ``warm'' by forcing transmissions roughly every minute in
     the absence of other activity.  An error is then indicated if no response
     can be elicited on an otherwise idle connection for a extended period
     (e.g., 5 minutes).  A SIGPIPE signal is raised if a process sends on a
     broken stream; this causes naive processes, which do not handle the sig-
     nal, to exit.

     SOCK_SEQPACKET sockets employ the same system calls as SOCK_STREAM sock-
     ets.  The only difference is that read(2) calls will return only the
     amount of data requested, and any remaining in the arriving packet will
     be discarded.

     SOCK_DGRAM and SOCK_RAW sockets allow sending of datagrams to correspon-
     dents named in send(2) calls.  Datagrams are generally received with
     recvfrom(2), which returns the next datagram with its return address.

     An fcntl(2) call can be used to specify a process group to receive a
     SIGURG signal when the out-of-band data arrives.  It may also enable non-
     blocking I/O and asynchronous notification of I/O events via SIGIO.

     The operation of sockets is controlled by socket level options.  These
     options are defined in the file <sys/socket.h>.  setsockopt(2) and
     getsockopt(2) are used to set and get options, respectively.

RETURN VALUES
     A -1 is returned if an error occurs, otherwise the return value is a
     descriptor referencing the socket.

ERRORS
     The socket() call fails if:

     [EPROTONOSUPPORT]  The protocol type or the specified protocol is not
                        supported within this domain.

     [EMFILE]           The per-process descriptor table is full.

     [ENFILE]           The system file table is full.

     [EACCES]           Permission to create a socket of the specified type
                        and/or protocol is denied.

     [ENOBUFS]          Insufficient buffer space is available.  The socket
                        cannot be created until sufficient resources are
                        freed.

SEE ALSO
     accept(2), bind(2), connect(2), getsockname(2), getsockopt(2), ioctl(2),
     listen(2), poll(2), read(2), recv(2), select(2), send(2), setsockopt(2),
     shutdown(2), socketpair(2), write(2), getprotoent(3), netintro(4)

     An Introductory 4.3 BSD Interprocess Communication Tutorial, reprinted in
     UNIX Programmer's Supplementary Documents Volume 1.

     BSD Interprocess Communication Tutorial, reprinted in UNIX Programmer's
     Supplementary Documents Volume 1.

HISTORY
     The socket() function call appeared in 4.2BSD.

BSD                              June 4, 1993                              BSD