1 @node Sockets, Low-Level Terminal Interface, Pipes and FIFOs, Top
2 @c %MENU% A more complicated IPC mechanism, with networking support
5 This chapter describes the GNU facilities for interprocess
6 communication using sockets.
9 @cindex interprocess communication, with sockets
10 A @dfn{socket} is a generalized interprocess communication channel.
11 Like a pipe, a socket is represented as a file descriptor. But,
12 unlike pipes, sockets support communication between unrelated
13 processes, and even between processes running on different machines
14 that communicate over a network. Sockets are the primary means of
15 communicating with other machines; @code{telnet}, @code{rlogin},
16 @code{ftp}, @code{talk}, and the other familiar network programs use
19 Not all operating systems support sockets. In the GNU library, the
20 header file @file{sys/socket.h} exists regardless of the operating
21 system, and the socket functions always exist, but if the system does
22 not really support sockets, these functions always fail.
24 @strong{Incomplete:} We do not currently document the facilities for
25 broadcast messages or for configuring Internet interfaces. The
26 reentrant functions and some newer functions that are related to IPv6
27 aren't documented either so far.
30 * Socket Concepts:: Basic concepts you need to know about.
31 * Communication Styles::Stream communication, datagrams, and other styles.
32 * Socket Addresses:: How socket names (``addresses'') work.
33 * Interface Naming:: Identifying specific network interfaces.
34 * Local Namespace:: Details about the local namespace.
35 * Internet Namespace:: Details about the Internet namespace.
36 * Misc Namespaces:: Other namespaces not documented fully here.
37 * Open/Close Sockets:: Creating sockets and destroying them.
38 * Connections:: Operations on sockets with connection state.
39 * Datagrams:: Operations on datagram sockets.
40 * Inetd:: Inetd is a daemon that starts servers on request.
41 The most convenient way to write a server
42 is to make it work with Inetd.
43 * Socket Options:: Miscellaneous low-level socket options.
44 * Networks Database:: Accessing the database of network names.
48 @section Socket Concepts
50 @cindex communication style (of a socket)
51 @cindex style of communication (of a socket)
52 When you create a socket, you must specify the style of communication
53 you want to use and the type of protocol that should implement it.
54 The @dfn{communication style} of a socket defines the user-level
55 semantics of sending and receiving data on the socket. Choosing a
56 communication style specifies the answers to questions such as these:
62 @cindex stream (sockets)
63 @strong{What are the units of data transmission?} Some communication
64 styles regard the data as a sequence of bytes, with no larger
65 structure; others group the bytes into records (which are known in
66 this context as @dfn{packets}).
69 @cindex loss of data on sockets
70 @cindex data loss on sockets
71 @strong{Can data be lost during normal operation?} Some communication
72 styles guarantee that all the data sent arrives in the order it was
73 sent (barring system or network crashes); other styles occasionally
74 lose data as a normal part of operation, and may sometimes deliver
75 packets more than once or in the wrong order.
77 Designing a program to use unreliable communication styles usually
78 involves taking precautions to detect lost or misordered packets and
79 to retransmit data as needed.
82 @strong{Is communication entirely with one partner?} Some
83 communication styles are like a telephone call---you make a
84 @dfn{connection} with one remote socket, and then exchange data
85 freely. Other styles are like mailing letters---you specify a
86 destination address for each message you send.
89 @cindex namespace (of socket)
90 @cindex domain (of socket)
91 @cindex socket namespace
93 You must also choose a @dfn{namespace} for naming the socket. A socket
94 name (``address'') is meaningful only in the context of a particular
95 namespace. In fact, even the data type to use for a socket name may
96 depend on the namespace. Namespaces are also called ``domains'', but we
97 avoid that word as it can be confused with other usage of the same
98 term. Each namespace has a symbolic name that starts with @samp{PF_}.
99 A corresponding symbolic name starting with @samp{AF_} designates the
100 address format for that namespace.
102 @cindex network protocol
103 @cindex protocol (of socket)
104 @cindex socket protocol
105 @cindex protocol family
106 Finally you must choose the @dfn{protocol} to carry out the
107 communication. The protocol determines what low-level mechanism is used
108 to transmit and receive data. Each protocol is valid for a particular
109 namespace and communication style; a namespace is sometimes called a
110 @dfn{protocol family} because of this, which is why the namespace names
111 start with @samp{PF_}.
113 The rules of a protocol apply to the data passing between two programs,
114 perhaps on different computers; most of these rules are handled by the
115 operating system, and you need not know about them. What you do need to
116 know about protocols is this:
120 In order to have communication between two sockets, they must specify
121 the @emph{same} protocol.
124 Each protocol is meaningful with particular style/namespace
125 combinations and cannot be used with inappropriate combinations. For
126 example, the TCP protocol fits only the byte stream style of
127 communication and the Internet namespace.
130 For each combination of style and namespace, there is a @dfn{default
131 protocol} which you can request by specifying 0 as the protocol
132 number. And that's what you should normally do---use the default.
135 Throughout the following description at various places
136 variables/parameters to denote sizes are required. And here the trouble
137 starts. In the first implementations the type of these variables was
138 simply @code{int}. This type was on almost all machines of this time 32
139 bits wide and so a de-factor standard required 32 bit variables. This
140 is important since references to variables of this type are passed to
143 But then the POSIX people came and unified the interface with the words
144 "all size values are of type @code{size_t}". But on 64 bit machines
145 @code{size_t} is 64 bits wide, and so variable references are not anymore
148 The Unix98 specification provides a solution by introducing a type
149 @code{socklen_t}. This type is used in all of the cases that POSIX
150 changed to use @code{size_t}. The only requirement of this type is that
151 it be an unsigned type of at least 32 bits. Therefore, implementations
152 which require that references to 32 bit variables be passed can be as
153 happy as implementations which use 64 bit values.
156 @node Communication Styles
157 @section Communication Styles
159 The GNU library includes support for several different kinds of sockets,
160 each with different characteristics. This section describes the
161 supported socket types. The symbolic constants listed here are
162 defined in @file{sys/socket.h}.
165 @comment sys/socket.h
167 @deftypevr Macro int SOCK_STREAM
168 The @code{SOCK_STREAM} style is like a pipe (@pxref{Pipes and FIFOs});
169 it operates over a connection with a particular remote socket, and
170 transmits data reliably as a stream of bytes.
172 Use of this style is covered in detail in @ref{Connections}.
175 @comment sys/socket.h
177 @deftypevr Macro int SOCK_DGRAM
178 The @code{SOCK_DGRAM} style is used for sending
179 individually-addressed packets, unreliably.
180 It is the diametrical opposite of @code{SOCK_STREAM}.
182 Each time you write data to a socket of this kind, that data becomes
183 one packet. Since @code{SOCK_DGRAM} sockets do not have connections,
184 you must specify the recipient address with each packet.
186 The only guarantee that the system makes about your requests to
187 transmit data is that it will try its best to deliver each packet you
188 send. It may succeed with the sixth packet after failing with the
189 fourth and fifth packets; the seventh packet may arrive before the
190 sixth, and may arrive a second time after the sixth.
192 The typical use for @code{SOCK_DGRAM} is in situations where it is
193 acceptable to simply resend a packet if no response is seen in a
194 reasonable amount of time.
196 @xref{Datagrams}, for detailed information about how to use datagram
201 @c This appears to be only for the NS domain, which we aren't
202 @c discussing and probably won't support either.
203 @comment sys/socket.h
205 @deftypevr Macro int SOCK_SEQPACKET
206 This style is like @code{SOCK_STREAM} except that the data is
207 structured into packets.
209 A program that receives data over a @code{SOCK_SEQPACKET} socket
210 should be prepared to read the entire message packet in a single call
211 to @code{read}; if it only reads part of the message, the remainder of
212 the message is simply discarded instead of being available for
213 subsequent calls to @code{read}.
215 Many protocols do not support this communication style.
220 @comment sys/socket.h
222 @deftypevr Macro int SOCK_RDM
223 This style is a reliable version of @code{SOCK_DGRAM}: it sends
224 individually addressed packets, but guarantees that each packet sent
225 arrives exactly once.
227 @strong{Warning:} It is not clear this is actually supported
228 by any operating system.
232 @comment sys/socket.h
234 @deftypevr Macro int SOCK_RAW
235 This style provides access to low-level network protocols and
236 interfaces. Ordinary user programs usually have no need to use this
240 @node Socket Addresses
241 @section Socket Addresses
243 @cindex address of socket
244 @cindex name of socket
245 @cindex binding a socket address
246 @cindex socket address (name) binding
247 The name of a socket is normally called an @dfn{address}. The
248 functions and symbols for dealing with socket addresses were named
249 inconsistently, sometimes using the term ``name'' and sometimes using
250 ``address''. You can regard these terms as synonymous where sockets
253 A socket newly created with the @code{socket} function has no
254 address. Other processes can find it for communication only if you
255 give it an address. We call this @dfn{binding} the address to the
256 socket, and the way to do it is with the @code{bind} function.
258 You need be concerned with the address of a socket if other processes
259 are to find it and start communicating with it. You can specify an
260 address for other sockets, but this is usually pointless; the first time
261 you send data from a socket, or use it to initiate a connection, the
262 system assigns an address automatically if you have not specified one.
264 Occasionally a client needs to specify an address because the server
265 discriminates based on addresses; for example, the rsh and rlogin
266 protocols look at the client's socket address and only bypass password
267 checking if it is less than @code{IPPORT_RESERVED} (@pxref{Ports}).
269 The details of socket addresses vary depending on what namespace you are
270 using. @xref{Local Namespace}, or @ref{Internet Namespace}, for specific
273 Regardless of the namespace, you use the same functions @code{bind} and
274 @code{getsockname} to set and examine a socket's address. These
275 functions use a phony data type, @code{struct sockaddr *}, to accept the
276 address. In practice, the address lives in a structure of some other
277 data type appropriate to the address format you are using, but you cast
278 its address to @code{struct sockaddr *} when you pass it to
282 * Address Formats:: About @code{struct sockaddr}.
283 * Setting Address:: Binding an address to a socket.
284 * Reading Address:: Reading the address of a socket.
287 @node Address Formats
288 @subsection Address Formats
290 The functions @code{bind} and @code{getsockname} use the generic data
291 type @code{struct sockaddr *} to represent a pointer to a socket
292 address. You can't use this data type effectively to interpret an
293 address or construct one; for that, you must use the proper data type
294 for the socket's namespace.
296 Thus, the usual practice is to construct an address in the proper
297 namespace-specific type, then cast a pointer to @code{struct sockaddr *}
298 when you call @code{bind} or @code{getsockname}.
300 The one piece of information that you can get from the @code{struct
301 sockaddr} data type is the @dfn{address format} designator which tells
302 you which data type to use to understand the address fully.
305 The symbols in this section are defined in the header file
308 @comment sys/socket.h
310 @deftp {Data Type} {struct sockaddr}
311 The @code{struct sockaddr} type itself has the following members:
314 @item short int sa_family
315 This is the code for the address format of this address. It
316 identifies the format of the data which follows.
318 @item char sa_data[14]
319 This is the actual socket address data, which is format-dependent. Its
320 length also depends on the format, and may well be more than 14. The
321 length 14 of @code{sa_data} is essentially arbitrary.
325 Each address format has a symbolic name which starts with @samp{AF_}.
326 Each of them corresponds to a @samp{PF_} symbol which designates the
327 corresponding namespace. Here is a list of address format names:
330 @comment sys/socket.h
334 This designates the address format that goes with the local namespace.
335 (@code{PF_LOCAL} is the name of that namespace.) @xref{Local Namespace
336 Details}, for information about this address format.
338 @comment sys/socket.h
342 This is a synonym for @code{AF_LOCAL}, for compatibility.
343 (@code{PF_UNIX} is likewise a synonym for @code{PF_LOCAL}.)
345 @comment sys/socket.h
349 This is another synonym for @code{AF_LOCAL}, for compatibility.
350 (@code{PF_FILE} is likewise a synonym for @code{PF_LOCAL}.)
352 @comment sys/socket.h
356 This designates the address format that goes with the Internet
357 namespace. (@code{PF_INET} is the name of that namespace.)
358 @xref{Internet Address Formats}.
360 @comment sys/socket.h
361 @comment IPv6 Basic API
363 This is similar to @code{AF_INET}, but refers to the IPv6 protocol.
364 (@code{PF_INET6} is the name of the corresponding namespace.)
366 @comment sys/socket.h
370 This designates no particular address format. It is used only in rare
371 cases, such as to clear out the default destination address of a
372 ``connected'' datagram socket. @xref{Sending Datagrams}.
374 The corresponding namespace designator symbol @code{PF_UNSPEC} exists
375 for completeness, but there is no reason to use it in a program.
378 @file{sys/socket.h} defines symbols starting with @samp{AF_} for many
379 different kinds of networks, all or most of which are not actually
380 implemented. We will document those that really work, as we receive
381 information about how to use them.
383 @node Setting Address
384 @subsection Setting the Address of a Socket
387 Use the @code{bind} function to assign an address to a socket. The
388 prototype for @code{bind} is in the header file @file{sys/socket.h}.
389 For examples of use, see @ref{Local Socket Example}, or see @ref{Inet Example}.
391 @comment sys/socket.h
393 @deftypefun int bind (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
394 The @code{bind} function assigns an address to the socket
395 @var{socket}. The @var{addr} and @var{length} arguments specify the
396 address; the detailed format of the address depends on the namespace.
397 The first part of the address is always the format designator, which
398 specifies a namespace, and says that the address is in the format for
401 The return value is @code{0} on success and @code{-1} on failure. The
402 following @code{errno} error conditions are defined for this function:
406 The @var{socket} argument is not a valid file descriptor.
409 The descriptor @var{socket} is not a socket.
412 The specified address is not available on this machine.
415 Some other socket is already using the specified address.
418 The socket @var{socket} already has an address.
421 You do not have permission to access the requested address. (In the
422 Internet domain, only the super-user is allowed to specify a port number
423 in the range 0 through @code{IPPORT_RESERVED} minus one; see
427 Additional conditions may be possible depending on the particular namespace
431 @node Reading Address
432 @subsection Reading the Address of a Socket
435 Use the function @code{getsockname} to examine the address of an
436 Internet socket. The prototype for this function is in the header file
439 @comment sys/socket.h
441 @deftypefun int getsockname (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
442 The @code{getsockname} function returns information about the
443 address of the socket @var{socket} in the locations specified by the
444 @var{addr} and @var{length-ptr} arguments. Note that the
445 @var{length-ptr} is a pointer; you should initialize it to be the
446 allocation size of @var{addr}, and on return it contains the actual
447 size of the address data.
449 The format of the address data depends on the socket namespace. The
450 length of the information is usually fixed for a given namespace, so
451 normally you can know exactly how much space is needed and can provide
452 that much. The usual practice is to allocate a place for the value
453 using the proper data type for the socket's namespace, then cast its
454 address to @code{struct sockaddr *} to pass it to @code{getsockname}.
456 The return value is @code{0} on success and @code{-1} on error. The
457 following @code{errno} error conditions are defined for this function:
461 The @var{socket} argument is not a valid file descriptor.
464 The descriptor @var{socket} is not a socket.
467 There are not enough internal buffers available for the operation.
471 You can't read the address of a socket in the file namespace. This is
472 consistent with the rest of the system; in general, there's no way to
473 find a file's name from a descriptor for that file.
475 @node Interface Naming
476 @section Interface Naming
478 Each network interface has a name. This usually consists of a few
479 letters that relate to the type of interface, which may be followed by a
480 number if there is more than one interface of that type. Examples
481 might be @code{lo} (the loopback interface) and @code{eth0} (the first
484 Although such names are convenient for humans, it would be clumsy to
485 have to use them whenever a program needs to refer to an interface. In
486 such situations an interface is referred to by its @dfn{index}, which is
487 an arbitrarily-assigned small positive integer.
489 The following functions, constants and data types are declared in the
490 header file @file{net/if.h}.
493 @deftypevr Constant size_t IFNAMSIZ
494 This constant defines the maximum buffer size needed to hold an
495 interface name, including its terminating zero byte.
499 @comment IPv6 basic API
500 @deftypefun {unsigned int} if_nametoindex (const char *ifname)
501 This function yields the interface index corresponding to a particular
502 name. If no interface exists with the name given, it returns 0.
506 @comment IPv6 basic API
507 @deftypefun {char *} if_indextoname (unsigned int ifindex, char *ifname)
508 This function maps an interface index to its corresponding name. The
509 returned name is placed in the buffer pointed to by @code{ifname}, which
510 must be at least @code{IFNAMSIZE} bytes in length. If the index was
511 invalid, the function's return value is a null pointer, otherwise it is
516 @comment IPv6 basic API
517 @deftp {Data Type} {struct if_nameindex}
518 This data type is used to hold the information about a single
519 interface. It has the following members:
522 @item unsigned int if_index;
523 This is the interface index.
526 This is the null-terminated index name.
532 @comment IPv6 basic API
533 @deftypefun {struct if_nameindex *} if_nameindex (void)
534 This function returns an array of @code{if_nameindex} structures, one
535 for every interface that is present. The end of the list is indicated
536 by a structure with an interface of 0 and a null name pointer. If an
537 error occurs, this function returns a null pointer.
539 The returned structure must be freed with @code{if_freenameindex} after
544 @comment IPv6 basic API
545 @deftypefun void if_freenameindex (struct if_nameindex *ptr)
546 This function frees the structure returned by an earlier call to
550 @node Local Namespace
551 @section The Local Namespace
552 @cindex local namespace, for sockets
554 This section describes the details of the local namespace, whose
555 symbolic name (required when you create a socket) is @code{PF_LOCAL}.
556 The local namespace is also known as ``Unix domain sockets''. Another
557 name is file namespace since socket addresses are normally implemented
561 * Concepts: Local Namespace Concepts. What you need to understand.
562 * Details: Local Namespace Details. Address format, symbolic names, etc.
563 * Example: Local Socket Example. Example of creating a socket.
566 @node Local Namespace Concepts
567 @subsection Local Namespace Concepts
569 In the local namespace, socket addresses are file names. You can specify
570 any file name you want as the address of the socket, but you must have
571 write permission on the directory containing it. In order to connect to
572 a socket, you must have read permission for it. It's common to put
573 these files in the @file{/tmp} directory.
575 One peculiarity of the local namespace is that the name is only used when
576 opening the connection; once that is over with, the address is not
577 meaningful and may not exist.
579 Another peculiarity is that you cannot connect to such a socket from
580 another machine--not even if the other machine shares the file system
581 which contains the name of the socket. You can see the socket in a
582 directory listing, but connecting to it never succeeds. Some programs
583 take advantage of this, such as by asking the client to send its own
584 process ID, and using the process IDs to distinguish between clients.
585 However, we recommend you not to use this method in protocols you design,
586 as we might someday permit connections from other machines that mount
587 the same file systems. Instead, send each new client an identifying
588 number if you want it to have one.
590 After you close a socket in the local namespace, you should delete the
591 file name from the file system. Use @code{unlink} or @code{remove} to
592 do this; see @ref{Deleting Files}.
594 The local namespace supports just one protocol for any communication
595 style; it is protocol number @code{0}.
597 @node Local Namespace Details
598 @subsection Details of Local Namespace
601 To create a socket in the local namespace, use the constant
602 @code{PF_LOCAL} as the @var{namespace} argument to @code{socket} or
603 @code{socketpair}. This constant is defined in @file{sys/socket.h}.
605 @comment sys/socket.h
607 @deftypevr Macro int PF_LOCAL
608 This designates the local namespace, in which socket addresses are local
609 names, and its associated family of protocols. @code{PF_Local} is the
610 macro used by Posix.1g.
613 @comment sys/socket.h
615 @deftypevr Macro int PF_UNIX
616 This is a synonym for @code{PF_LOCAL}, for compatibility's sake.
619 @comment sys/socket.h
621 @deftypevr Macro int PF_FILE
622 This is a synonym for @code{PF_LOCAL}, for compatibility's sake.
625 The structure for specifying socket names in the local namespace is
626 defined in the header file @file{sys/un.h}:
631 @deftp {Data Type} {struct sockaddr_un}
632 This structure is used to specify local namespace socket addresses. It has
633 the following members:
636 @item short int sun_family
637 This identifies the address family or format of the socket address.
638 You should store the value @code{AF_LOCAL} to designate the local
639 namespace. @xref{Socket Addresses}.
641 @item char sun_path[108]
642 This is the file name to use.
644 @strong{Incomplete:} Why is 108 a magic number? RMS suggests making
645 this a zero-length array and tweaking the example following to use
646 @code{alloca} to allocate an appropriate amount of storage based on
647 the length of the filename.
651 You should compute the @var{length} parameter for a socket address in
652 the local namespace as the sum of the size of the @code{sun_family}
653 component and the string length (@emph{not} the allocation size!) of
654 the file name string. This can be done using the macro @code{SUN_LEN}:
658 @deftypefn {Macro} int SUN_LEN (@emph{struct sockaddr_un *} @var{ptr})
659 The macro computes the length of socket address in the local namespace.
662 @node Local Socket Example
663 @subsection Example of Local-Namespace Sockets
665 Here is an example showing how to create and name a socket in the local
669 @include mkfsock.c.texi
672 @node Internet Namespace
673 @section The Internet Namespace
674 @cindex Internet namespace, for sockets
676 This section describes the details of the protocols and socket naming
677 conventions used in the Internet namespace.
679 Originaly the Internet namespace used only IP version 4 (IPv4). With
680 the growing number of hosts on the Internet, a new protocol with a
681 larger address space was neccessary: IP version 6 (IPv6). IPv6
682 introduces besides 128bit addresses (IPv4 has 32bit addresses) also
683 other features and will eventually replace IPv4.
685 To create a socket in the IPv4 Internet namespace, use the symbolic name
686 @code{PF_INET} of this namespace as the @var{namespace} argument to
687 @code{socket} or @code{socketpair}. For IPv6 addresses, you need the
688 macro @code{PF_INET6}. These macros are defined in @file{sys/socket.h}.
691 @comment sys/socket.h
693 @deftypevr Macro int PF_INET
694 This designates the IPv4 Internet namespace and associated family of
698 @deftypevr Macro int AF_INET6
699 This designates the IPv6 Internet namespace and associated family of
703 A socket address for the Internet namespace includes the following components:
707 The address of the machine you want to connect to. Internet addresses
708 can be specified in several ways; these are discussed in @ref{Internet
709 Address Formats}, @ref{Host Addresses}, and @ref{Host Names}.
712 A port number for that machine. @xref{Ports}.
715 You must ensure that the address and port number are represented in a
716 canonical format called @dfn{network byte order}. @xref{Byte Order},
717 for information about this.
720 * Internet Address Formats:: How socket addresses are specified in the
722 * Host Addresses:: All about host addresses of internet host.
723 * Protocols Database:: Referring to protocols by name.
724 * Ports:: Internet port numbers.
725 * Services Database:: Ports may have symbolic names.
726 * Byte Order:: Different hosts may use different byte
727 ordering conventions; you need to
728 canonicalize host address and port number.
729 * Inet Example:: Putting it all together.
732 @node Internet Address Formats
733 @subsection Internet Socket Address Formats
735 In the Internet namespace, for both IPv4 (@code{AF_INET}) and IPv6
736 (@code{AF_INET6}), a socket address consists of a host address
737 and a port on that host. In addition, the protocol you choose serves
738 effectively as a part of the address because local port numbers are
739 meaningful only within a particular protocol.
741 The data types for representing socket addresses in the Internet namespace
742 are defined in the header file @file{netinet/in.h}.
745 @comment netinet/in.h
747 @deftp {Data Type} {struct sockaddr_in}
748 This is the data type used to represent socket addresses in the
749 Internet namespace. It has the following members:
752 @item sa_family_t sin_family
753 This identifies the address family or format of the socket address.
754 You should store the value of @code{AF_INET} in this member.
755 @xref{Socket Addresses}.
757 @item struct in_addr sin_addr
758 This is the Internet address of the host machine. @xref{Host
759 Addresses}, and @ref{Host Names}, for how to get a value to store
762 @item unsigned short int sin_port
763 This is the port number. @xref{Ports}.
767 When you call @code{bind} or @code{getsockname}, you should specify
768 @code{sizeof (struct sockaddr_in)} as the @var{length} parameter if
769 you are using an IPv4 Internet namespace socket address.
771 @deftp {Data Type} {struct sockaddr_in6}
772 This is the data type used to represent socket addresses in the IPv6
773 namespace. It has the following members:
776 @item sa_family_t sin6_family
777 This identifies the address family or format of the socket address.
778 You should store the value of @code{AF_INET6} in this member.
779 @xref{Socket Addresses}.
781 @item struct in6_addr sin6_addr
782 This is the IPv6 address of the host machine. @xref{Host
783 Addresses}, and @ref{Host Names}, for how to get a value to store
786 @item uint32_t sin6_flowinfo
787 This is a currently unimplemented field.
789 @item uint16_t sin6_port
790 This is the port number. @xref{Ports}.
796 @subsection Host Addresses
798 Each computer on the Internet has one or more @dfn{Internet addresses},
799 numbers which identify that computer among all those on the Internet.
800 Users typically write IPv4 numeric host addresses as sequences of four
801 numbers, separated by periods, as in @samp{128.52.46.32}, and IPv6
802 numeric host addresses as sequences of up to eight numbers separated by
803 colons, as in @samp{5f03:1200:836f:c100::1}.
805 Each computer also has one or more @dfn{host names}, which are strings
806 of words separated by periods, as in @samp{mescaline.gnu.org}.
808 Programs that let the user specify a host typically accept both numeric
809 addresses and host names. But the program needs a numeric address to
810 open a connection; to use a host name, you must convert it to the
811 numeric address it stands for.
814 * Abstract Host Addresses:: What a host number consists of.
815 * Data type: Host Address Data Type. Data type for a host number.
816 * Functions: Host Address Functions. Functions to operate on them.
817 * Names: Host Names. Translating host names to host numbers.
820 @node Abstract Host Addresses
821 @subsubsection Internet Host Addresses
822 @cindex host address, Internet
823 @cindex Internet host address
826 Each computer on the Internet has one or more Internet addresses,
827 numbers which identify that computer among all those on the Internet.
830 @cindex network number
831 @cindex local network address number
832 An IPv4 Internet host address is a number containing four bytes of data.
833 Historically these are divided into two parts, a @dfn{network number} and a
834 @dfn{local network address number} within that network. In the
835 mid-1990s classless address were introduced which changed the
836 behaviour. Since some functions implicitly expect the old definitions,
837 we first describe the class based network and will then describe
838 classless addresses. IPv6 uses only classless adresses and therefore
839 the following paragraphs don't apply.
841 The class based IPv4 network number consists of the first one, two or
842 three bytes; the rest of the bytes are the local address.
844 IPv4 network numbers are registered with the Network Information Center
845 (NIC), and are divided into three classes---A, B, and C. The local
846 network address numbers of individual machines are registered with the
847 administrator of the particular network.
849 Class A networks have single-byte numbers in the range 0 to 127. There
850 are only a small number of Class A networks, but they can each support a
851 very large number of hosts. Medium-sized Class B networks have two-byte
852 network numbers, with the first byte in the range 128 to 191. Class C
853 networks are the smallest; they have three-byte network numbers, with
854 the first byte in the range 192-255. Thus, the first 1, 2, or 3 bytes
855 of an Internet address specifies a network. The remaining bytes of the
856 Internet address specify the address within that network.
858 The Class A network 0 is reserved for broadcast to all networks. In
859 addition, the host number 0 within each network is reserved for broadcast
860 to all hosts in that network. These uses are obsolete now but out of
861 compatibility reasons you shouldn't use network 0 and host number 0.
863 The Class A network 127 is reserved for loopback; you can always use
864 the Internet address @samp{127.0.0.1} to refer to the host machine.
866 Since a single machine can be a member of multiple networks, it can
867 have multiple Internet host addresses. However, there is never
868 supposed to be more than one machine with the same host address.
870 @c !!! this section could document the IN_CLASS* macros in <netinet/in.h>.
871 @c No, it shouldn't since they're obsolete.
873 @cindex standard dot notation, for Internet addresses
874 @cindex dot notation, for Internet addresses
875 There are four forms of the @dfn{standard numbers-and-dots notation}
876 for Internet addresses:
879 @item @var{a}.@var{b}.@var{c}.@var{d}
880 This specifies all four bytes of the address individually and is the
881 commonly used representation.
883 @item @var{a}.@var{b}.@var{c}
884 The last part of the address, @var{c}, is interpreted as a 2-byte quantity.
885 This is useful for specifying host addresses in a Class B network with
886 network address number @code{@var{a}.@var{b}}.
888 @item @var{a}.@var{b}
889 The last part of the address, @var{b}, is interpreted as a 3-byte quantity.
890 This is useful for specifying host addresses in a Class A network with
891 network address number @var{a}.
894 If only one part is given, this corresponds directly to the host address
898 Within each part of the address, the usual C conventions for specifying
899 the radix apply. In other words, a leading @samp{0x} or @samp{0X} implies
900 hexadecimal radix; a leading @samp{0} implies octal; and otherwise decimal
903 @subsubheading Classless Addresses
905 IPv4 addresses (and IPv6 addresses also) are now considered as
906 classless. The distinction between classes A, B, and C can be ignored.
907 Instead a IPv4 host adddress consists of a 32-bit address and a 32-bit
908 mask. The mask contains bits of 1 for the network part and bits of 0
909 for the host part. The 1-bits are contigous from the leftmost bit, the
910 0-bits are contigous from the rightmost bit so that the netmask can also
911 be written as a prefix length of bits of 1. Classes A, B and C are just
912 special cases of this general rule. For example, class A addresses have
913 a netmask of @samp{255.0.0.0} or a prefix length of 8.
915 Classless IPv4 network addresses are written in numbers-and-dots
916 notation with the prefix length appended and a slash as separator. For
917 example the class A network 10 is written as @samp{10.0.0.0/8}.
919 @subsubheading IPv6 Addresses
921 IPv6 addresses contain 128 bits (IPv4 has 32 bits) of data. A host
922 address is usually written as eight 16-bit hexadecimal numbers that are
923 separated by colons. Two colons are used to abbreviate strings of
924 consecutive zeros. For example the IPv6 loopback address which is
925 @samp{0:0:0:0:0:0:0:1} can be just written as @samp{::1}.
927 @node Host Address Data Type
928 @subsubsection Host Address Data Type
930 IPv4 Internet host addresses are represented in some contexts as integers
931 (type @code{uint32_t}). In other contexts, the integer is
932 packaged inside a structure of type @code{struct in_addr}. It would
933 be better if the usage were made consistent, but it is not hard to extract
934 the integer from the structure or put the integer into a structure.
936 You will find older code that uses @code{unsigned long int} for
937 IPv4 Internet host addresses instead of @code{uint32_t} or @code{struct
938 in_addr}. Historically @code{unsigned long int} was a 32 bit number but
939 with 64 bit machines this has changed. Using @code{unsigned long int}
940 might break the code if it is used on machines where this type doesn't
941 have 32 bits. @code{uint32_t} is specified by Unix98 and guaranteed to have
944 IPv6 Internet host addresses have 128 bits and are packaged inside a
945 structure of type @code{struct in6_addr}.
947 The following basic definitions for Internet addresses are declared in
948 the header file @file{netinet/in.h}:
951 @comment netinet/in.h
953 @deftp {Data Type} {struct in_addr}
954 This data type is used in certain contexts to contain an IPv4 Internet
955 host address. It has just one field, named @code{s_addr}, which records
956 the host address number as an @code{uint32_t}.
959 @comment netinet/in.h
961 @deftypevr Macro {uint32_t} INADDR_LOOPBACK
962 You can use this constant to stand for ``the address of this machine,''
963 instead of finding its actual address. It is the IPv4 Internet address
964 @samp{127.0.0.1}, which is usually called @samp{localhost}. This
965 special constant saves you the trouble of looking up the address of your
966 own machine. Also, the system usually implements @code{INADDR_LOOPBACK}
967 specially, avoiding any network traffic for the case of one machine
971 @comment netinet/in.h
973 @deftypevr Macro {uint32_t} INADDR_ANY
974 You can use this constant to stand for ``any incoming address,'' when
975 binding to an address. @xref{Setting Address}. This is the usual
976 address to give in the @code{sin_addr} member of @w{@code{struct
977 sockaddr_in}} when you want to accept Internet connections.
980 @comment netinet/in.h
982 @deftypevr Macro {uint32_t} INADDR_BROADCAST
983 This constant is the address you use to send a broadcast message.
984 @c !!! broadcast needs further documented
987 @comment netinet/in.h
989 @deftypevr Macro {uint32_t} INADDR_NONE
990 This constant is returned by some functions to indicate an error.
993 @comment netinet/in.h
994 @comment IPv6 basic API
995 @deftp {Data Type} {struct in6_addr}
996 This data type is used to store an IPv6 address. It stores 128 bits of
997 data, which can be accessed (via a union) in a variety of ways.
1000 @comment netinet/in.h
1001 @comment IPv6 basic API
1002 @deftypevr Constant {struct in6_addr} in6addr_loopback
1003 This constant is the IPv6 address @samp{::1}, the loopback address. See
1004 above for a description of what this means. The macro
1005 @code{IN6ADDR_LOOPBACK_INIT} is provided to allow you to initialise your
1006 own variables to this value.
1009 @comment netinet/in.h
1010 @comment IPv6 basic API
1011 @deftypevr Constant {struct in6_addr} in6addr_any
1012 This constant is the IPv6 address @samp{::}, the unspecified address. See
1013 above for a description of what this means. The macro
1014 @code{IN6ADDR_ANY_INIT} is provided to allow you to initialise your
1015 own variables to this value.
1018 @node Host Address Functions
1019 @subsubsection Host Address Functions
1023 These additional functions for manipulating Internet addresses are
1024 declared in the header file @file{arpa/inet.h}. They represent Internet
1025 addresses in network byte order; they represent network numbers and
1026 local-address-within-network numbers in host byte order. @xref{Byte
1027 Order}, for an explanation of network and host byte order.
1029 @comment arpa/inet.h
1031 @deftypefun int inet_aton (const char *@var{name}, struct in_addr *@var{addr})
1032 This function converts the IPv4 Internet host address @var{name}
1033 from the standard numbers-and-dots notation into binary data and stores
1034 it in the @code{struct in_addr} that @var{addr} points to.
1035 @code{inet_aton} returns nonzero if the address is valid, zero if not.
1038 @comment arpa/inet.h
1040 @deftypefun {uint32_t} inet_addr (const char *@var{name})
1041 This function converts the IPv4 Internet host address @var{name} from the
1042 standard numbers-and-dots notation into binary data. If the input is
1043 not valid, @code{inet_addr} returns @code{INADDR_NONE}. This is an
1044 obsolete interface to @code{inet_aton}, described immediately above; it
1045 is obsolete because @code{INADDR_NONE} is a valid address
1046 (255.255.255.255), and @code{inet_aton} provides a cleaner way to
1047 indicate error return.
1050 @comment arpa/inet.h
1052 @deftypefun {uint32_t} inet_network (const char *@var{name})
1053 This function extracts the network number from the address @var{name},
1054 given in the standard numbers-and-dots notation. The returned address is
1055 in host order. If the input is not valid, @code{inet_network} returns
1058 The function works only with traditional IPv4 class A, B and C network
1059 types. It doesn't work with classless addresses and shouldn't be used
1063 @comment arpa/inet.h
1065 @deftypefun {char *} inet_ntoa (struct in_addr @var{addr})
1066 This function converts the IPv4 Internet host address @var{addr} to a
1067 string in the standard numbers-and-dots notation. The return value is
1068 a pointer into a statically-allocated buffer. Subsequent calls will
1069 overwrite the same buffer, so you should copy the string if you need
1072 In multi-threaded programs each thread has an own statically-allocated
1073 buffer. But still subsequent calls of @code{inet_ntoa} in the same
1074 thread will overwrite the result of the last call.
1076 Instead of @code{inet_ntoa} the newer function @code{inet_ntop} which is
1077 described below should be used since it handles both IPv4 and IPv6
1081 @comment arpa/inet.h
1083 @deftypefun {struct in_addr} inet_makeaddr (uint32_t @var{net}, uint32_t @var{local})
1084 This function makes an IPv4 Internet host address by combining the network
1085 number @var{net} with the local-address-within-network number
1089 @comment arpa/inet.h
1091 @deftypefun uint32_t inet_lnaof (struct in_addr @var{addr})
1092 This function returns the local-address-within-network part of the
1093 Internet host address @var{addr}.
1095 The function works only with traditional IPv4 class A, B and C network
1096 types. It doesn't work with classless addresses and shouldn't be used
1100 @comment arpa/inet.h
1102 @deftypefun uint32_t inet_netof (struct in_addr @var{addr})
1103 This function returns the network number part of the Internet host
1106 The function works only with traditional IPv4 class A, B and C network
1107 types. It doesn't work with classless addresses and shouldn't be used
1111 @comment arpa/inet.h
1112 @comment IPv6 basic API
1113 @deftypefun int inet_pton (int @var{af}, const char *@var{cp}, void *@var{buf})
1114 This function converts an Internet address (either IPv4 or IPv6) from
1115 presentation (textual) to network (binary) format. @var{af} should be
1116 either @code{AF_INET} or @code{AF_INET6}, as appropriate for the type of
1117 address being converted. @var{cp} is a pointer to the input string, and
1118 @var{buf} is a pointer to a buffer for the result. It is the caller's
1119 responsibility to make sure the buffer is large enough.
1122 @comment arpa/inet.h
1123 @comment IPv6 basic API
1124 @deftypefun {const char *} inet_ntop (int @var{af}, const void *@var{cp}, char *@var{buf}, size_t @var{len})
1125 This function converts an Internet address (either IPv4 or IPv6) from
1126 network (binary) to presentation (textual) form. @var{af} should be
1127 either @code{AF_INET} or @code{AF_INET6}, as appropriate. @var{cp} is a
1128 pointer to the address to be converted. @var{buf} should be a pointer
1129 to a buffer to hold the result, and @var{len} is the length of this
1130 buffer. The return value from the function will be this buffer address.
1134 @subsubsection Host Names
1135 @cindex hosts database
1136 @cindex converting host name to address
1137 @cindex converting host address to name
1139 Besides the standard numbers-and-dots notation for Internet addresses,
1140 you can also refer to a host by a symbolic name. The advantage of a
1141 symbolic name is that it is usually easier to remember. For example,
1142 the machine with Internet address @samp{158.121.106.19} is also known as
1143 @samp{alpha.gnu.org}; and other machines in the @samp{gnu.org}
1144 domain can refer to it simply as @samp{alpha}.
1148 Internally, the system uses a database to keep track of the mapping
1149 between host names and host numbers. This database is usually either
1150 the file @file{/etc/hosts} or an equivalent provided by a name server.
1151 The functions and other symbols for accessing this database are declared
1152 in @file{netdb.h}. They are BSD features, defined unconditionally if
1153 you include @file{netdb.h}.
1157 @deftp {Data Type} {struct hostent}
1158 This data type is used to represent an entry in the hosts database. It
1159 has the following members:
1163 This is the ``official'' name of the host.
1165 @item char **h_aliases
1166 These are alternative names for the host, represented as a null-terminated
1169 @item int h_addrtype
1170 This is the host address type; in practice, its value is always either
1171 @code{AF_INET} or @code{AF_INET6}, with the latter being used for IPv6
1172 hosts. In principle other kinds of addresses could be represented in
1173 the data base as well as Internet addresses; if this were done, you
1174 might find a value in this field other than @code{AF_INET} or
1175 @code{AF_INET6}. @xref{Socket Addresses}.
1178 This is the length, in bytes, of each address.
1180 @item char **h_addr_list
1181 This is the vector of addresses for the host. (Recall that the host
1182 might be connected to multiple networks and have different addresses on
1183 each one.) The vector is terminated by a null pointer.
1186 This is a synonym for @code{h_addr_list[0]}; in other words, it is the
1191 As far as the host database is concerned, each address is just a block
1192 of memory @code{h_length} bytes long. But in other contexts there is an
1193 implicit assumption that you can convert IPv4 addresses to a
1194 @code{struct in_addr} or an @code{uint32_t}. Host addresses in
1195 a @code{struct hostent} structure are always given in network byte
1196 order; see @ref{Byte Order}.
1198 You can use @code{gethostbyname}, @code{gethostbyname2} or
1199 @code{gethostbyaddr} to search the hosts database for information about
1200 a particular host. The information is returned in a
1201 statically-allocated structure; you must copy the information if you
1202 need to save it across calls. You can also use @code{getaddrinfo} and
1203 @code{getnameinfo} to obtain this information.
1207 @deftypefun {struct hostent *} gethostbyname (const char *@var{name})
1208 The @code{gethostbyname} function returns information about the host
1209 named @var{name}. If the lookup fails, it returns a null pointer.
1213 @comment IPv6 Basic API
1214 @deftypefun {struct hostent *} gethostbyname2 (const char *@var{name}, int @var{af})
1215 The @code{gethostbyname2} function is like @code{gethostbyname}, but
1216 allows the caller to specify the desired address family (e.g.@:
1217 @code{AF_INET} or @code{AF_INET6}) for the result.
1222 @deftypefun {struct hostent *} gethostbyaddr (const char *@var{addr}, int @var{length}, int @var{format})
1223 The @code{gethostbyaddr} function returns information about the host
1224 with Internet address @var{addr}. The parameter @var{addr} is not
1225 really a pointer to char - it can be a pointer to an IPv4 or an IPv6
1226 address. The @var{length} argument is the size (in bytes) of the address
1227 at @var{addr}. @var{format} specifies the address format; for an IPv4
1228 Internet address, specify a value of @code{AF_INET}; for an IPv6
1229 Internet address, use @code{AF_INET6}.
1231 If the lookup fails, @code{gethostbyaddr} returns a null pointer.
1235 If the name lookup by @code{gethostbyname} or @code{gethostbyaddr}
1236 fails, you can find out the reason by looking at the value of the
1237 variable @code{h_errno}. (It would be cleaner design for these
1238 functions to set @code{errno}, but use of @code{h_errno} is compatible
1239 with other systems.) Before using @code{h_errno}, you must declare it
1246 Here are the error codes that you may find in @code{h_errno}:
1251 @item HOST_NOT_FOUND
1252 @vindex HOST_NOT_FOUND
1253 No such host is known in the data base.
1259 This condition happens when the name server could not be contacted. If
1260 you try again later, you may succeed then.
1266 A non-recoverable error occurred.
1272 The host database contains an entry for the name, but it doesn't have an
1273 associated Internet address.
1276 You can also scan the entire hosts database one entry at a time using
1277 @code{sethostent}, @code{gethostent}, and @code{endhostent}. Be careful
1278 in using these functions, because they are not reentrant.
1282 @deftypefun void sethostent (int @var{stayopen})
1283 This function opens the hosts database to begin scanning it. You can
1284 then call @code{gethostent} to read the entries.
1286 @c There was a rumor that this flag has different meaning if using the DNS,
1287 @c but it appears this description is accurate in that case also.
1288 If the @var{stayopen} argument is nonzero, this sets a flag so that
1289 subsequent calls to @code{gethostbyname} or @code{gethostbyaddr} will
1290 not close the database (as they usually would). This makes for more
1291 efficiency if you call those functions several times, by avoiding
1292 reopening the database for each call.
1297 @deftypefun {struct hostent *} gethostent (void)
1298 This function returns the next entry in the hosts database. It
1299 returns a null pointer if there are no more entries.
1304 @deftypefun void endhostent (void)
1305 This function closes the hosts database.
1309 @subsection Internet Ports
1312 A socket address in the Internet namespace consists of a machine's
1313 Internet address plus a @dfn{port number} which distinguishes the
1314 sockets on a given machine (for a given protocol). Port numbers range
1317 Port numbers less than @code{IPPORT_RESERVED} are reserved for standard
1318 servers, such as @code{finger} and @code{telnet}. There is a database
1319 that keeps track of these, and you can use the @code{getservbyname}
1320 function to map a service name onto a port number; see @ref{Services
1323 If you write a server that is not one of the standard ones defined in
1324 the database, you must choose a port number for it. Use a number
1325 greater than @code{IPPORT_USERRESERVED}; such numbers are reserved for
1326 servers and won't ever be generated automatically by the system.
1327 Avoiding conflicts with servers being run by other users is up to you.
1329 When you use a socket without specifying its address, the system
1330 generates a port number for it. This number is between
1331 @code{IPPORT_RESERVED} and @code{IPPORT_USERRESERVED}.
1333 On the Internet, it is actually legitimate to have two different
1334 sockets with the same port number, as long as they never both try to
1335 communicate with the same socket address (host address plus port
1336 number). You shouldn't duplicate a port number except in special
1337 circumstances where a higher-level protocol requires it. Normally,
1338 the system won't let you do it; @code{bind} normally insists on
1339 distinct port numbers. To reuse a port number, you must set the
1340 socket option @code{SO_REUSEADDR}. @xref{Socket-Level Options}.
1342 @pindex netinet/in.h
1343 These macros are defined in the header file @file{netinet/in.h}.
1345 @comment netinet/in.h
1347 @deftypevr Macro int IPPORT_RESERVED
1348 Port numbers less than @code{IPPORT_RESERVED} are reserved for
1352 @comment netinet/in.h
1354 @deftypevr Macro int IPPORT_USERRESERVED
1355 Port numbers greater than or equal to @code{IPPORT_USERRESERVED} are
1356 reserved for explicit use; they will never be allocated automatically.
1359 @node Services Database
1360 @subsection The Services Database
1361 @cindex services database
1362 @cindex converting service name to port number
1363 @cindex converting port number to service name
1365 @pindex /etc/services
1366 The database that keeps track of ``well-known'' services is usually
1367 either the file @file{/etc/services} or an equivalent from a name server.
1368 You can use these utilities, declared in @file{netdb.h}, to access
1369 the services database.
1374 @deftp {Data Type} {struct servent}
1375 This data type holds information about entries from the services database.
1376 It has the following members:
1380 This is the ``official'' name of the service.
1382 @item char **s_aliases
1383 These are alternate names for the service, represented as an array of
1384 strings. A null pointer terminates the array.
1387 This is the port number for the service. Port numbers are given in
1388 network byte order; see @ref{Byte Order}.
1391 This is the name of the protocol to use with this service.
1392 @xref{Protocols Database}.
1396 To get information about a particular service, use the
1397 @code{getservbyname} or @code{getservbyport} functions. The information
1398 is returned in a statically-allocated structure; you must copy the
1399 information if you need to save it across calls.
1403 @deftypefun {struct servent *} getservbyname (const char *@var{name}, const char *@var{proto})
1404 The @code{getservbyname} function returns information about the
1405 service named @var{name} using protocol @var{proto}. If it can't find
1406 such a service, it returns a null pointer.
1408 This function is useful for servers as well as for clients; servers
1409 use it to determine which port they should listen on (@pxref{Listening}).
1414 @deftypefun {struct servent *} getservbyport (int @var{port}, const char *@var{proto})
1415 The @code{getservbyport} function returns information about the
1416 service at port @var{port} using protocol @var{proto}. If it can't
1417 find such a service, it returns a null pointer.
1421 You can also scan the services database using @code{setservent},
1422 @code{getservent}, and @code{endservent}. Be careful in using these
1423 functions, because they are not reentrant.
1427 @deftypefun void setservent (int @var{stayopen})
1428 This function opens the services database to begin scanning it.
1430 If the @var{stayopen} argument is nonzero, this sets a flag so that
1431 subsequent calls to @code{getservbyname} or @code{getservbyport} will
1432 not close the database (as they usually would). This makes for more
1433 efficiency if you call those functions several times, by avoiding
1434 reopening the database for each call.
1439 @deftypefun {struct servent *} getservent (void)
1440 This function returns the next entry in the services database. If
1441 there are no more entries, it returns a null pointer.
1446 @deftypefun void endservent (void)
1447 This function closes the services database.
1451 @subsection Byte Order Conversion
1452 @cindex byte order conversion, for socket
1453 @cindex converting byte order
1456 @cindex little-endian
1457 Different kinds of computers use different conventions for the
1458 ordering of bytes within a word. Some computers put the most
1459 significant byte within a word first (this is called ``big-endian''
1460 order), and others put it last (``little-endian'' order).
1462 @cindex network byte order
1463 So that machines with different byte order conventions can
1464 communicate, the Internet protocols specify a canonical byte order
1465 convention for data transmitted over the network. This is known
1466 as the @dfn{network byte order}.
1468 When establishing an Internet socket connection, you must make sure that
1469 the data in the @code{sin_port} and @code{sin_addr} members of the
1470 @code{sockaddr_in} structure are represented in the network byte order.
1471 If you are encoding integer data in the messages sent through the
1472 socket, you should convert this to network byte order too. If you don't
1473 do this, your program may fail when running on or talking to other kinds
1476 If you use @code{getservbyname} and @code{gethostbyname} or
1477 @code{inet_addr} to get the port number and host address, the values are
1478 already in the network byte order, and you can copy them directly into
1479 the @code{sockaddr_in} structure.
1481 Otherwise, you have to convert the values explicitly. Use @code{htons}
1482 and @code{ntohs} to convert values for the @code{sin_port} member. Use
1483 @code{htonl} and @code{ntohl} to convert IPv4 addresses for the
1484 @code{sin_addr} member. (Remember, @code{struct in_addr} is equivalent
1485 to @code{uint32_t}.) These functions are declared in
1486 @file{netinet/in.h}.
1487 @pindex netinet/in.h
1489 @comment netinet/in.h
1491 @deftypefun {uint16_t} htons (uint16_t @var{hostshort})
1492 This function converts the @code{uint16_t} integer @var{hostshort} from
1493 host byte order to network byte order.
1496 @comment netinet/in.h
1498 @deftypefun {uint16_t} ntohs (uint16_t @var{netshort})
1499 This function converts the @code{uint16_t} integer @var{netshort} from
1500 network byte order to host byte order.
1503 @comment netinet/in.h
1505 @deftypefun {uint32_t} htonl (uint32_t @var{hostlong})
1506 This function converts the @code{uint32_t} integer @var{hostlong} from
1507 host byte order to network byte order.
1509 This is used for IPv4 internet addresses.
1512 @comment netinet/in.h
1514 @deftypefun {uint32_t} ntohl (uint32_t @var{netlong})
1515 This function converts the @code{uint32_t} integer @var{netlong} from
1516 network byte order to host byte order.
1518 This is used for IPv4 internet addresses.
1521 @node Protocols Database
1522 @subsection Protocols Database
1523 @cindex protocols database
1525 The communications protocol used with a socket controls low-level
1526 details of how data is exchanged. For example, the protocol implements
1527 things like checksums to detect errors in transmissions, and routing
1528 instructions for messages. Normal user programs have little reason to
1529 mess with these details directly.
1531 @cindex TCP (Internet protocol)
1532 The default communications protocol for the Internet namespace depends on
1533 the communication style. For stream communication, the default is TCP
1534 (``transmission control protocol''). For datagram communication, the
1535 default is UDP (``user datagram protocol''). For reliable datagram
1536 communication, the default is RDP (``reliable datagram protocol'').
1537 You should nearly always use the default.
1539 @pindex /etc/protocols
1540 Internet protocols are generally specified by a name instead of a
1541 number. The network protocols that a host knows about are stored in a
1542 database. This is usually either derived from the file
1543 @file{/etc/protocols}, or it may be an equivalent provided by a name
1544 server. You look up the protocol number associated with a named
1545 protocol in the database using the @code{getprotobyname} function.
1547 Here are detailed descriptions of the utilities for accessing the
1548 protocols database. These are declared in @file{netdb.h}.
1553 @deftp {Data Type} {struct protoent}
1554 This data type is used to represent entries in the network protocols
1555 database. It has the following members:
1559 This is the official name of the protocol.
1561 @item char **p_aliases
1562 These are alternate names for the protocol, specified as an array of
1563 strings. The last element of the array is a null pointer.
1566 This is the protocol number (in host byte order); use this member as the
1567 @var{protocol} argument to @code{socket}.
1571 You can use @code{getprotobyname} and @code{getprotobynumber} to search
1572 the protocols database for a specific protocol. The information is
1573 returned in a statically-allocated structure; you must copy the
1574 information if you need to save it across calls.
1578 @deftypefun {struct protoent *} getprotobyname (const char *@var{name})
1579 The @code{getprotobyname} function returns information about the
1580 network protocol named @var{name}. If there is no such protocol, it
1581 returns a null pointer.
1586 @deftypefun {struct protoent *} getprotobynumber (int @var{protocol})
1587 The @code{getprotobynumber} function returns information about the
1588 network protocol with number @var{protocol}. If there is no such
1589 protocol, it returns a null pointer.
1592 You can also scan the whole protocols database one protocol at a time by
1593 using @code{setprotoent}, @code{getprotoent}, and @code{endprotoent}.
1594 Be careful in using these functions, because they are not reentrant.
1598 @deftypefun void setprotoent (int @var{stayopen})
1599 This function opens the protocols database to begin scanning it.
1601 If the @var{stayopen} argument is nonzero, this sets a flag so that
1602 subsequent calls to @code{getprotobyname} or @code{getprotobynumber} will
1603 not close the database (as they usually would). This makes for more
1604 efficiency if you call those functions several times, by avoiding
1605 reopening the database for each call.
1610 @deftypefun {struct protoent *} getprotoent (void)
1611 This function returns the next entry in the protocols database. It
1612 returns a null pointer if there are no more entries.
1617 @deftypefun void endprotoent (void)
1618 This function closes the protocols database.
1622 @subsection Internet Socket Example
1624 Here is an example showing how to create and name a socket in the
1625 Internet namespace. The newly created socket exists on the machine that
1626 the program is running on. Rather than finding and using the machine's
1627 Internet address, this example specifies @code{INADDR_ANY} as the host
1628 address; the system replaces that with the machine's actual address.
1631 @include mkisock.c.texi
1634 Here is another example, showing how you can fill in a @code{sockaddr_in}
1635 structure, given a host name string and a port number:
1638 @include isockad.c.texi
1641 @node Misc Namespaces
1642 @section Other Namespaces
1649 Certain other namespaces and associated protocol families are supported
1650 but not documented yet because they are not often used. @code{PF_NS}
1651 refers to the Xerox Network Software protocols. @code{PF_ISO} stands
1652 for Open Systems Interconnect. @code{PF_CCITT} refers to protocols from
1653 CCITT. @file{socket.h} defines these symbols and others naming protocols
1654 not actually implemented.
1656 @code{PF_IMPLINK} is used for communicating between hosts and Internet
1657 Message Processors. For information on this, and on @code{PF_ROUTE}, an
1658 occasionally-used local area routing protocol, see the GNU Hurd Manual
1659 (to appear in the future).
1661 @node Open/Close Sockets
1662 @section Opening and Closing Sockets
1664 This section describes the actual library functions for opening and
1665 closing sockets. The same functions work for all namespaces and
1669 * Creating a Socket:: How to open a socket.
1670 * Closing a Socket:: How to close a socket.
1671 * Socket Pairs:: These are created like pipes.
1674 @node Creating a Socket
1675 @subsection Creating a Socket
1676 @cindex creating a socket
1677 @cindex socket, creating
1678 @cindex opening a socket
1680 The primitive for creating a socket is the @code{socket} function,
1681 declared in @file{sys/socket.h}.
1682 @pindex sys/socket.h
1684 @comment sys/socket.h
1686 @deftypefun int socket (int @var{namespace}, int @var{style}, int @var{protocol})
1687 This function creates a socket and specifies communication style
1688 @var{style}, which should be one of the socket styles listed in
1689 @ref{Communication Styles}. The @var{namespace} argument specifies
1690 the namespace; it must be @code{PF_LOCAL} (@pxref{Local Namespace}) or
1691 @code{PF_INET} (@pxref{Internet Namespace}). @var{protocol}
1692 designates the specific protocol (@pxref{Socket Concepts}); zero is
1693 usually right for @var{protocol}.
1695 The return value from @code{socket} is the file descriptor for the new
1696 socket, or @code{-1} in case of error. The following @code{errno} error
1697 conditions are defined for this function:
1700 @item EPROTONOSUPPORT
1701 The @var{protocol} or @var{style} is not supported by the
1702 @var{namespace} specified.
1705 The process already has too many file descriptors open.
1708 The system already has too many file descriptors open.
1711 The process does not have privilege to create a socket of the specified
1712 @var{style} or @var{protocol}.
1715 The system ran out of internal buffer space.
1718 The file descriptor returned by the @code{socket} function supports both
1719 read and write operations. But, like pipes, sockets do not support file
1720 positioning operations.
1723 For examples of how to call the @code{socket} function,
1724 see @ref{Local Socket Example}, or @ref{Inet Example}.
1727 @node Closing a Socket
1728 @subsection Closing a Socket
1729 @cindex socket, closing
1730 @cindex closing a socket
1731 @cindex shutting down a socket
1732 @cindex socket shutdown
1734 When you are finished using a socket, you can simply close its
1735 file descriptor with @code{close}; see @ref{Opening and Closing Files}.
1736 If there is still data waiting to be transmitted over the connection,
1737 normally @code{close} tries to complete this transmission. You
1738 can control this behavior using the @code{SO_LINGER} socket option to
1739 specify a timeout period; see @ref{Socket Options}.
1741 @pindex sys/socket.h
1742 You can also shut down only reception or only transmission on a
1743 connection by calling @code{shutdown}, which is declared in
1744 @file{sys/socket.h}.
1746 @comment sys/socket.h
1748 @deftypefun int shutdown (int @var{socket}, int @var{how})
1749 The @code{shutdown} function shuts down the connection of socket
1750 @var{socket}. The argument @var{how} specifies what action to
1755 Stop receiving data for this socket. If further data arrives,
1759 Stop trying to transmit data from this socket. Discard any data
1760 waiting to be sent. Stop looking for acknowledgement of data already
1761 sent; don't retransmit it if it is lost.
1764 Stop both reception and transmission.
1767 The return value is @code{0} on success and @code{-1} on failure. The
1768 following @code{errno} error conditions are defined for this function:
1772 @var{socket} is not a valid file descriptor.
1775 @var{socket} is not a socket.
1778 @var{socket} is not connected.
1783 @subsection Socket Pairs
1784 @cindex creating a socket pair
1786 @cindex opening a socket pair
1788 @pindex sys/socket.h
1789 A @dfn{socket pair} consists of a pair of connected (but unnamed)
1790 sockets. It is very similar to a pipe and is used in much the same
1791 way. Socket pairs are created with the @code{socketpair} function,
1792 declared in @file{sys/socket.h}. A socket pair is much like a pipe; the
1793 main difference is that the socket pair is bidirectional, whereas the
1794 pipe has one input-only end and one output-only end (@pxref{Pipes and
1797 @comment sys/socket.h
1799 @deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})
1800 This function creates a socket pair, returning the file descriptors in
1801 @code{@var{filedes}[0]} and @code{@var{filedes}[1]}. The socket pair
1802 is a full-duplex communications channel, so that both reading and writing
1803 may be performed at either end.
1805 The @var{namespace}, @var{style}, and @var{protocol} arguments are
1806 interpreted as for the @code{socket} function. @var{style} should be
1807 one of the communication styles listed in @ref{Communication Styles}.
1808 The @var{namespace} argument specifies the namespace, which must be
1809 @code{AF_LOCAL} (@pxref{Local Namespace}); @var{protocol} specifies the
1810 communications protocol, but zero is the only meaningful value.
1812 If @var{style} specifies a connectionless communication style, then
1813 the two sockets you get are not @emph{connected}, strictly speaking,
1814 but each of them knows the other as the default destination address,
1815 so they can send packets to each other.
1817 The @code{socketpair} function returns @code{0} on success and @code{-1}
1818 on failure. The following @code{errno} error conditions are defined
1823 The process has too many file descriptors open.
1826 The specified namespace is not supported.
1828 @item EPROTONOSUPPORT
1829 The specified protocol is not supported.
1832 The specified protocol does not support the creation of socket pairs.
1837 @section Using Sockets with Connections
1842 The most common communication styles involve making a connection to a
1843 particular other socket, and then exchanging data with that socket
1844 over and over. Making a connection is asymmetric; one side (the
1845 @dfn{client}) acts to request a connection, while the other side (the
1846 @dfn{server}) makes a socket and waits for the connection request.
1851 @ref{Connecting}, describes what the client program must do to
1852 initiate a connection with a server.
1855 @ref{Listening}, and @ref{Accepting Connections}, describe what the
1856 server program must do to wait for and act upon connection requests
1860 @ref{Transferring Data}, describes how data is transferred through the
1866 * Connecting:: What the client program must do.
1867 * Listening:: How a server program waits for requests.
1868 * Accepting Connections:: What the server does when it gets a request.
1869 * Who is Connected:: Getting the address of the
1870 other side of a connection.
1871 * Transferring Data:: How to send and receive data.
1872 * Byte Stream Example:: An example program: a client for communicating
1873 over a byte stream socket in the Internet namespace.
1874 * Server Example:: A corresponding server program.
1875 * Out-of-Band Data:: This is an advanced feature.
1879 @subsection Making a Connection
1880 @cindex connecting a socket
1881 @cindex socket, connecting
1882 @cindex socket, initiating a connection
1883 @cindex socket, client actions
1885 In making a connection, the client makes a connection while the server
1886 waits for and accepts the connection. Here we discuss what the client
1887 program must do, using the @code{connect} function, which is declared in
1888 @file{sys/socket.h}.
1890 @comment sys/socket.h
1892 @deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
1893 The @code{connect} function initiates a connection from the socket
1894 with file descriptor @var{socket} to the socket whose address is
1895 specified by the @var{addr} and @var{length} arguments. (This socket
1896 is typically on another machine, and it must be already set up as a
1897 server.) @xref{Socket Addresses}, for information about how these
1898 arguments are interpreted.
1900 Normally, @code{connect} waits until the server responds to the request
1901 before it returns. You can set nonblocking mode on the socket
1902 @var{socket} to make @code{connect} return immediately without waiting
1903 for the response. @xref{File Status Flags}, for information about
1905 @c !!! how do you tell when it has finished connecting? I suspect the
1906 @c way you do it is select for writing.
1908 The normal return value from @code{connect} is @code{0}. If an error
1909 occurs, @code{connect} returns @code{-1}. The following @code{errno}
1910 error conditions are defined for this function:
1914 The socket @var{socket} is not a valid file descriptor.
1917 File descriptor @var{socket} is not a socket.
1920 The specified address is not available on the remote machine.
1923 The namespace of the @var{addr} is not supported by this socket.
1926 The socket @var{socket} is already connected.
1929 The attempt to establish the connection timed out.
1932 The server has actively refused to establish the connection.
1935 The network of the given @var{addr} isn't reachable from this host.
1938 The socket address of the given @var{addr} is already in use.
1941 The socket @var{socket} is non-blocking and the connection could not be
1942 established immediately. You can determine when the connection is
1943 completely established with @code{select}; @pxref{Waiting for I/O}.
1944 Another @code{connect} call on the same socket, before the connection is
1945 completely established, will fail with @code{EALREADY}.
1948 The socket @var{socket} is non-blocking and already has a pending
1949 connection in progress (see @code{EINPROGRESS} above).
1952 This function is defined as a cancelation point in multi-threaded
1953 programs. So one has to be prepared for this and make sure that
1954 possibly allocated resources (like memory, files descriptors,
1955 semaphores or whatever) are freed even if the thread is canceled.
1956 @c @xref{pthread_cleanup_push}, for a method how to do this.
1960 @subsection Listening for Connections
1961 @cindex listening (sockets)
1962 @cindex sockets, server actions
1963 @cindex sockets, listening
1965 Now let us consider what the server process must do to accept
1966 connections on a socket. First it must use the @code{listen} function
1967 to enable connection requests on the socket, and then accept each
1968 incoming connection with a call to @code{accept} (@pxref{Accepting
1969 Connections}). Once connection requests are enabled on a server socket,
1970 the @code{select} function reports when the socket has a connection
1971 ready to be accepted (@pxref{Waiting for I/O}).
1973 The @code{listen} function is not allowed for sockets using
1974 connectionless communication styles.
1976 You can write a network server that does not even start running until a
1977 connection to it is requested. @xref{Inetd Servers}.
1979 In the Internet namespace, there are no special protection mechanisms
1980 for controlling access to connect to a port; any process on any machine
1981 can make a connection to your server. If you want to restrict access to
1982 your server, make it examine the addresses associated with connection
1983 requests or implement some other handshaking or identification
1986 In the local namespace, the ordinary file protection bits control who has
1987 access to connect to the socket.
1989 @comment sys/socket.h
1991 @deftypefun int listen (int @var{socket}, unsigned int @var{n})
1992 The @code{listen} function enables the socket @var{socket} to accept
1993 connections, thus making it a server socket.
1995 The argument @var{n} specifies the length of the queue for pending
1996 connections. When the queue fills, new clients attempting to connect
1997 fail with @code{ECONNREFUSED} until the server calls @code{accept} to
1998 accept a connection from the queue.
2000 The @code{listen} function returns @code{0} on success and @code{-1}
2001 on failure. The following @code{errno} error conditions are defined
2006 The argument @var{socket} is not a valid file descriptor.
2009 The argument @var{socket} is not a socket.
2012 The socket @var{socket} does not support this operation.
2016 @node Accepting Connections
2017 @subsection Accepting Connections
2018 @cindex sockets, accepting connections
2019 @cindex accepting connections
2021 When a server receives a connection request, it can complete the
2022 connection by accepting the request. Use the function @code{accept}
2025 A socket that has been established as a server can accept connection
2026 requests from multiple clients. The server's original socket
2027 @emph{does not become part} of the connection; instead, @code{accept}
2028 makes a new socket which participates in the connection.
2029 @code{accept} returns the descriptor for this socket. The server's
2030 original socket remains available for listening for further connection
2033 The number of pending connection requests on a server socket is finite.
2034 If connection requests arrive from clients faster than the server can
2035 act upon them, the queue can fill up and additional requests are refused
2036 with a @code{ECONNREFUSED} error. You can specify the maximum length of
2037 this queue as an argument to the @code{listen} function, although the
2038 system may also impose its own internal limit on the length of this
2041 @comment sys/socket.h
2043 @deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length_ptr})
2044 This function is used to accept a connection request on the server
2045 socket @var{socket}.
2047 The @code{accept} function waits if there are no connections pending,
2048 unless the socket @var{socket} has nonblocking mode set. (You can use
2049 @code{select} to wait for a pending connection, with a nonblocking
2050 socket.) @xref{File Status Flags}, for information about nonblocking
2053 The @var{addr} and @var{length-ptr} arguments are used to return
2054 information about the name of the client socket that initiated the
2055 connection. @xref{Socket Addresses}, for information about the format
2058 Accepting a connection does not make @var{socket} part of the
2059 connection. Instead, it creates a new socket which becomes
2060 connected. The normal return value of @code{accept} is the file
2061 descriptor for the new socket.
2063 After @code{accept}, the original socket @var{socket} remains open and
2064 unconnected, and continues listening until you close it. You can
2065 accept further connections with @var{socket} by calling @code{accept}
2068 If an error occurs, @code{accept} returns @code{-1}. The following
2069 @code{errno} error conditions are defined for this function:
2073 The @var{socket} argument is not a valid file descriptor.
2076 The descriptor @var{socket} argument is not a socket.
2079 The descriptor @var{socket} does not support this operation.
2082 @var{socket} has nonblocking mode set, and there are no pending
2083 connections immediately available.
2086 This function is defined as a cancelation point in multi-threaded
2087 programs. So one has to be prepared for this and make sure that
2088 possibly allocated resources (like memory, files descriptors,
2089 semaphores or whatever) are freed even if the thread is canceled.
2090 @c @xref{pthread_cleanup_push}, for a method how to do this.
2093 The @code{accept} function is not allowed for sockets using
2094 connectionless communication styles.
2096 @node Who is Connected
2097 @subsection Who is Connected to Me?
2099 @comment sys/socket.h
2101 @deftypefun int getpeername (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
2102 The @code{getpeername} function returns the address of the socket that
2103 @var{socket} is connected to; it stores the address in the memory space
2104 specified by @var{addr} and @var{length-ptr}. It stores the length of
2105 the address in @code{*@var{length-ptr}}.
2107 @xref{Socket Addresses}, for information about the format of the
2108 address. In some operating systems, @code{getpeername} works only for
2109 sockets in the Internet domain.
2111 The return value is @code{0} on success and @code{-1} on error. The
2112 following @code{errno} error conditions are defined for this function:
2116 The argument @var{socket} is not a valid file descriptor.
2119 The descriptor @var{socket} is not a socket.
2122 The socket @var{socket} is not connected.
2125 There are not enough internal buffers available.
2130 @node Transferring Data
2131 @subsection Transferring Data
2132 @cindex reading from a socket
2133 @cindex writing to a socket
2135 Once a socket has been connected to a peer, you can use the ordinary
2136 @code{read} and @code{write} operations (@pxref{I/O Primitives}) to
2137 transfer data. A socket is a two-way communications channel, so read
2138 and write operations can be performed at either end.
2140 There are also some I/O modes that are specific to socket operations.
2141 In order to specify these modes, you must use the @code{recv} and
2142 @code{send} functions instead of the more generic @code{read} and
2143 @code{write} functions. The @code{recv} and @code{send} functions take
2144 an additional argument which you can use to specify various flags to
2145 control the special I/O modes. For example, you can specify the
2146 @code{MSG_OOB} flag to read or write out-of-band data, the
2147 @code{MSG_PEEK} flag to peek at input, or the @code{MSG_DONTROUTE} flag
2148 to control inclusion of routing information on output.
2151 * Sending Data:: Sending data with @code{send}.
2152 * Receiving Data:: Reading data with @code{recv}.
2153 * Socket Data Options:: Using @code{send} and @code{recv}.
2157 @subsubsection Sending Data
2159 @pindex sys/socket.h
2160 The @code{send} function is declared in the header file
2161 @file{sys/socket.h}. If your @var{flags} argument is zero, you can just
2162 as well use @code{write} instead of @code{send}; see @ref{I/O
2163 Primitives}. If the socket was connected but the connection has broken,
2164 you get a @code{SIGPIPE} signal for any use of @code{send} or
2165 @code{write} (@pxref{Miscellaneous Signals}).
2167 @comment sys/socket.h
2169 @deftypefun int send (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2170 The @code{send} function is like @code{write}, but with the additional
2171 flags @var{flags}. The possible values of @var{flags} are described
2172 in @ref{Socket Data Options}.
2174 This function returns the number of bytes transmitted, or @code{-1} on
2175 failure. If the socket is nonblocking, then @code{send} (like
2176 @code{write}) can return after sending just part of the data.
2177 @xref{File Status Flags}, for information about nonblocking mode.
2179 Note, however, that a successful return value merely indicates that
2180 the message has been sent without error, not necessarily that it has
2181 been received without error.
2183 The following @code{errno} error conditions are defined for this function:
2187 The @var{socket} argument is not a valid file descriptor.
2190 The operation was interrupted by a signal before any data was sent.
2191 @xref{Interrupted Primitives}.
2194 The descriptor @var{socket} is not a socket.
2197 The socket type requires that the message be sent atomically, but the
2198 message is too large for this to be possible.
2201 Nonblocking mode has been set on the socket, and the write operation
2202 would block. (Normally @code{send} blocks until the operation can be
2206 There is not enough internal buffer space available.
2209 You never connected this socket.
2212 This socket was connected but the connection is now broken. In this
2213 case, @code{send} generates a @code{SIGPIPE} signal first; if that
2214 signal is ignored or blocked, or if its handler returns, then
2215 @code{send} fails with @code{EPIPE}.
2218 This function is defined as a cancelation point in multi-threaded
2219 programs. So one has to be prepared for this and make sure that
2220 possibly allocated resources (like memory, files descriptors,
2221 semaphores or whatever) are freed even if the thread is canceled.
2222 @c @xref{pthread_cleanup_push}, for a method how to do this.
2225 @node Receiving Data
2226 @subsubsection Receiving Data
2228 @pindex sys/socket.h
2229 The @code{recv} function is declared in the header file
2230 @file{sys/socket.h}. If your @var{flags} argument is zero, you can
2231 just as well use @code{read} instead of @code{recv}; see @ref{I/O
2234 @comment sys/socket.h
2236 @deftypefun int recv (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2237 The @code{recv} function is like @code{read}, but with the additional
2238 flags @var{flags}. The possible values of @var{flags} are described
2239 in @ref{Socket Data Options}.
2241 If nonblocking mode is set for @var{socket}, and no data is available to
2242 be read, @code{recv} fails immediately rather than waiting. @xref{File
2243 Status Flags}, for information about nonblocking mode.
2245 This function returns the number of bytes received, or @code{-1} on failure.
2246 The following @code{errno} error conditions are defined for this function:
2250 The @var{socket} argument is not a valid file descriptor.
2253 The descriptor @var{socket} is not a socket.
2256 Nonblocking mode has been set on the socket, and the read operation
2257 would block. (Normally, @code{recv} blocks until there is input
2258 available to be read.)
2261 The operation was interrupted by a signal before any data was read.
2262 @xref{Interrupted Primitives}.
2265 You never connected this socket.
2268 This function is defined as a cancelation point in multi-threaded
2269 programs. So one has to be prepared for this and make sure that
2270 possibly allocated resources (like memory, files descriptors,
2271 semaphores or whatever) are freed even if the thread is canceled.
2272 @c @xref{pthread_cleanup_push}, for a method how to do this.
2275 @node Socket Data Options
2276 @subsubsection Socket Data Options
2278 @pindex sys/socket.h
2279 The @var{flags} argument to @code{send} and @code{recv} is a bit
2280 mask. You can bitwise-OR the values of the following macros together
2281 to obtain a value for this argument. All are defined in the header
2282 file @file{sys/socket.h}.
2284 @comment sys/socket.h
2286 @deftypevr Macro int MSG_OOB
2287 Send or receive out-of-band data. @xref{Out-of-Band Data}.
2290 @comment sys/socket.h
2292 @deftypevr Macro int MSG_PEEK
2293 Look at the data but don't remove it from the input queue. This is
2294 only meaningful with input functions such as @code{recv}, not with
2298 @comment sys/socket.h
2300 @deftypevr Macro int MSG_DONTROUTE
2301 Don't include routing information in the message. This is only
2302 meaningful with output operations, and is usually only of interest for
2303 diagnostic or routing programs. We don't try to explain it here.
2306 @node Byte Stream Example
2307 @subsection Byte Stream Socket Example
2309 Here is an example client program that makes a connection for a byte
2310 stream socket in the Internet namespace. It doesn't do anything
2311 particularly interesting once it has connected to the server; it just
2312 sends a text string to the server and exits.
2314 This program uses @code{init_sockaddr} to set up the socket address; see
2318 @include inetcli.c.texi
2321 @node Server Example
2322 @subsection Byte Stream Connection Server Example
2324 The server end is much more complicated. Since we want to allow
2325 multiple clients to be connected to the server at the same time, it
2326 would be incorrect to wait for input from a single client by simply
2327 calling @code{read} or @code{recv}. Instead, the right thing to do is
2328 to use @code{select} (@pxref{Waiting for I/O}) to wait for input on
2329 all of the open sockets. This also allows the server to deal with
2330 additional connection requests.
2332 This particular server doesn't do anything interesting once it has
2333 gotten a message from a client. It does close the socket for that
2334 client when it detects an end-of-file condition (resulting from the
2335 client shutting down its end of the connection).
2337 This program uses @code{make_socket} to set up the socket address; see
2341 @include inetsrv.c.texi
2344 @node Out-of-Band Data
2345 @subsection Out-of-Band Data
2347 @cindex out-of-band data
2348 @cindex high-priority data
2349 Streams with connections permit @dfn{out-of-band} data that is
2350 delivered with higher priority than ordinary data. Typically the
2351 reason for sending out-of-band data is to send notice of an
2352 exceptional condition. The way to send out-of-band data is using
2353 @code{send}, specifying the flag @code{MSG_OOB} (@pxref{Sending
2356 Out-of-band data is received with higher priority because the
2357 receiving process need not read it in sequence; to read the next
2358 available out-of-band data, use @code{recv} with the @code{MSG_OOB}
2359 flag (@pxref{Receiving Data}). Ordinary read operations do not read
2360 out-of-band data; they read only the ordinary data.
2362 @cindex urgent socket condition
2363 When a socket finds that out-of-band data is on its way, it sends a
2364 @code{SIGURG} signal to the owner process or process group of the
2365 socket. You can specify the owner using the @code{F_SETOWN} command
2366 to the @code{fcntl} function; see @ref{Interrupt Input}. You must
2367 also establish a handler for this signal, as described in @ref{Signal
2368 Handling}, in order to take appropriate action such as reading the
2371 Alternatively, you can test for pending out-of-band data, or wait
2372 until there is out-of-band data, using the @code{select} function; it
2373 can wait for an exceptional condition on the socket. @xref{Waiting
2374 for I/O}, for more information about @code{select}.
2376 Notification of out-of-band data (whether with @code{SIGURG} or with
2377 @code{select}) indicates that out-of-band data is on the way; the data
2378 may not actually arrive until later. If you try to read the
2379 out-of-band data before it arrives, @code{recv} fails with an
2380 @code{EWOULDBLOCK} error.
2382 Sending out-of-band data automatically places a ``mark'' in the stream
2383 of ordinary data, showing where in the sequence the out-of-band data
2384 ``would have been''. This is useful when the meaning of out-of-band
2385 data is ``cancel everything sent so far''. Here is how you can test,
2386 in the receiving process, whether any ordinary data was sent before
2390 success = ioctl (socket, SIOCATMARK, &atmark);
2393 The @code{integer} variable @var{atmark} is set to a nonzero value if
2394 the socket's read pointer has reached the ``mark''.
2396 @c Posix 1.g specifies sockatmark for this ioctl. sockatmark is not
2399 Here's a function to discard any ordinary data preceding the
2404 discard_until_mark (int socket)
2408 /* @r{This is not an arbitrary limit; any size will do.} */
2410 int atmark, success;
2412 /* @r{If we have reached the mark, return.} */
2413 success = ioctl (socket, SIOCATMARK, &atmark);
2419 /* @r{Otherwise, read a bunch of ordinary data and discard it.}
2420 @r{This is guaranteed not to read past the mark}
2421 @r{if it starts before the mark.} */
2422 success = read (socket, buffer, sizeof buffer);
2429 If you don't want to discard the ordinary data preceding the mark, you
2430 may need to read some of it anyway, to make room in internal system
2431 buffers for the out-of-band data. If you try to read out-of-band data
2432 and get an @code{EWOULDBLOCK} error, try reading some ordinary data
2433 (saving it so that you can use it when you want it) and see if that
2434 makes room. Here is an example:
2441 struct buffer *next;
2444 /* @r{Read the out-of-band data from SOCKET and return it}
2445 @r{as a `struct buffer', which records the address of the data}
2448 @r{It may be necessary to read some ordinary data}
2449 @r{in order to make room for the out-of-band data.}
2450 @r{If so, the ordinary data is saved as a chain of buffers}
2451 @r{found in the `next' field of the value.} */
2454 read_oob (int socket)
2456 struct buffer *tail = 0;
2457 struct buffer *list = 0;
2461 /* @r{This is an arbitrary limit.}
2462 @r{Does anyone know how to do this without a limit?} */
2463 char *buffer = (char *) xmalloc (1024);
2467 /* @r{Try again to read the out-of-band data.} */
2468 success = recv (socket, buffer, sizeof buffer, MSG_OOB);
2471 /* @r{We got it, so return it.} */
2473 = (struct buffer *) xmalloc (sizeof (struct buffer));
2474 link->buffer = buffer;
2475 link->size = success;
2480 /* @r{If we fail, see if we are at the mark.} */
2481 success = ioctl (socket, SIOCATMARK, &atmark);
2486 /* @r{At the mark; skipping past more ordinary data cannot help.}
2487 @r{So just wait a while.} */
2492 /* @r{Otherwise, read a bunch of ordinary data and save it.}
2493 @r{This is guaranteed not to read past the mark}
2494 @r{if it starts before the mark.} */
2495 success = read (socket, buffer, sizeof buffer);
2499 /* @r{Save this data in the buffer list.} */
2502 = (struct buffer *) xmalloc (sizeof (struct buffer));
2503 link->buffer = buffer;
2504 link->size = success;
2506 /* @r{Add the new link to the end of the list.} */
2518 @section Datagram Socket Operations
2520 @cindex datagram socket
2521 This section describes how to use communication styles that don't use
2522 connections (styles @code{SOCK_DGRAM} and @code{SOCK_RDM}). Using
2523 these styles, you group data into packets and each packet is an
2524 independent communication. You specify the destination for each
2525 packet individually.
2527 Datagram packets are like letters: you send each one independently,
2528 with its own destination address, and they may arrive in the wrong
2529 order or not at all.
2531 The @code{listen} and @code{accept} functions are not allowed for
2532 sockets using connectionless communication styles.
2535 * Sending Datagrams:: Sending packets on a datagram socket.
2536 * Receiving Datagrams:: Receiving packets on a datagram socket.
2537 * Datagram Example:: An example program: packets sent over a
2538 datagram socket in the local namespace.
2539 * Example Receiver:: Another program, that receives those packets.
2542 @node Sending Datagrams
2543 @subsection Sending Datagrams
2544 @cindex sending a datagram
2545 @cindex transmitting datagrams
2546 @cindex datagrams, transmitting
2548 @pindex sys/socket.h
2549 The normal way of sending data on a datagram socket is by using the
2550 @code{sendto} function, declared in @file{sys/socket.h}.
2552 You can call @code{connect} on a datagram socket, but this only
2553 specifies a default destination for further data transmission on the
2554 socket. When a socket has a default destination, then you can use
2555 @code{send} (@pxref{Sending Data}) or even @code{write} (@pxref{I/O
2556 Primitives}) to send a packet there. You can cancel the default
2557 destination by calling @code{connect} using an address format of
2558 @code{AF_UNSPEC} in the @var{addr} argument. @xref{Connecting}, for
2559 more information about the @code{connect} function.
2561 @comment sys/socket.h
2563 @deftypefun int sendto (int @var{socket}, void *@var{buffer}. size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, socklen_t @var{length})
2564 The @code{sendto} function transmits the data in the @var{buffer}
2565 through the socket @var{socket} to the destination address specified
2566 by the @var{addr} and @var{length} arguments. The @var{size} argument
2567 specifies the number of bytes to be transmitted.
2569 The @var{flags} are interpreted the same way as for @code{send}; see
2570 @ref{Socket Data Options}.
2572 The return value and error conditions are also the same as for
2573 @code{send}, but you cannot rely on the system to detect errors and
2574 report them; the most common error is that the packet is lost or there
2575 is no one at the specified address to receive it, and the operating
2576 system on your machine usually does not know this.
2578 It is also possible for one call to @code{sendto} to report an error
2579 due to a problem related to a previous call.
2581 This function is defined as a cancelation point in multi-threaded
2582 programs. So one has to be prepared for this and make sure that
2583 possibly allocated resources (like memory, files descriptors,
2584 semaphores or whatever) are freed even if the thread is canceled.
2585 @c @xref{pthread_cleanup_push}, for a method how to do this.
2588 @node Receiving Datagrams
2589 @subsection Receiving Datagrams
2590 @cindex receiving datagrams
2592 The @code{recvfrom} function reads a packet from a datagram socket and
2593 also tells you where it was sent from. This function is declared in
2594 @file{sys/socket.h}.
2596 @comment sys/socket.h
2598 @deftypefun int recvfrom (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
2599 The @code{recvfrom} function reads one packet from the socket
2600 @var{socket} into the buffer @var{buffer}. The @var{size} argument
2601 specifies the maximum number of bytes to be read.
2603 If the packet is longer than @var{size} bytes, then you get the first
2604 @var{size} bytes of the packet, and the rest of the packet is lost.
2605 There's no way to read the rest of the packet. Thus, when you use a
2606 packet protocol, you must always know how long a packet to expect.
2608 The @var{addr} and @var{length-ptr} arguments are used to return the
2609 address where the packet came from. @xref{Socket Addresses}. For a
2610 socket in the local domain, the address information won't be meaningful,
2611 since you can't read the address of such a socket (@pxref{Local
2612 Namespace}). You can specify a null pointer as the @var{addr} argument
2613 if you are not interested in this information.
2615 The @var{flags} are interpreted the same way as for @code{recv}
2616 (@pxref{Socket Data Options}). The return value and error conditions
2617 are also the same as for @code{recv}.
2619 This function is defined as a cancelation point in multi-threaded
2620 programs. So one has to be prepared for this and make sure that
2621 possibly allocated resources (like memory, files descriptors,
2622 semaphores or whatever) are freed even if the thread is canceled.
2623 @c @xref{pthread_cleanup_push}, for a method how to do this.
2626 You can use plain @code{recv} (@pxref{Receiving Data}) instead of
2627 @code{recvfrom} if you know don't need to find out who sent the packet
2628 (either because you know where it should come from or because you
2629 treat all possible senders alike). Even @code{read} can be used if
2630 you don't want to specify @var{flags} (@pxref{I/O Primitives}).
2633 @c sendmsg and recvmsg are like readv and writev in that they
2634 @c use a series of buffers. It's not clear this is worth
2635 @c supporting or that we support them.
2636 @c !!! they can do more; it is hairy
2638 @comment sys/socket.h
2640 @deftp {Data Type} {struct msghdr}
2643 @comment sys/socket.h
2645 @deftypefun int sendmsg (int @var{socket}, const struct msghdr *@var{message}, int @var{flags})
2647 This function is defined as a cancelation point in multi-threaded
2648 programs. So one has to be prepared for this and make sure that
2649 possibly allocated resources (like memory, files descriptors,
2650 semaphores or whatever) are freed even if the thread is cancel.
2651 @c @xref{pthread_cleanup_push}, for a method how to do this.
2654 @comment sys/socket.h
2656 @deftypefun int recvmsg (int @var{socket}, struct msghdr *@var{message}, int @var{flags})
2658 This function is defined as a cancelation point in multi-threaded
2659 programs. So one has to be prepared for this and make sure that
2660 possibly allocated resources (like memory, files descriptors,
2661 semaphores or whatever) are freed even if the thread is canceled.
2662 @c @xref{pthread_cleanup_push}, for a method how to do this.
2666 @node Datagram Example
2667 @subsection Datagram Socket Example
2669 Here is a set of example programs that send messages over a datagram
2670 stream in the local namespace. Both the client and server programs use
2671 the @code{make_named_socket} function that was presented in @ref{Local
2672 Socket Example}, to create and name their sockets.
2674 First, here is the server program. It sits in a loop waiting for
2675 messages to arrive, bouncing each message back to the sender.
2676 Obviously, this isn't a particularly useful program, but it does show
2677 the general ideas involved.
2680 @include filesrv.c.texi
2683 @node Example Receiver
2684 @subsection Example of Reading Datagrams
2686 Here is the client program corresponding to the server above.
2688 It sends a datagram to the server and then waits for a reply. Notice
2689 that the socket for the client (as well as for the server) in this
2690 example has to be given a name. This is so that the server can direct
2691 a message back to the client. Since the socket has no associated
2692 connection state, the only way the server can do this is by
2693 referencing the name of the client.
2696 @include filecli.c.texi
2699 Keep in mind that datagram socket communications are unreliable. In
2700 this example, the client program waits indefinitely if the message
2701 never reaches the server or if the server's response never comes
2702 back. It's up to the user running the program to kill it and restart
2703 it, if desired. A more automatic solution could be to use
2704 @code{select} (@pxref{Waiting for I/O}) to establish a timeout period
2705 for the reply, and in case of timeout either resend the message or
2706 shut down the socket and exit.
2709 @section The @code{inetd} Daemon
2711 We've explained above how to write a server program that does its own
2712 listening. Such a server must already be running in order for anyone
2715 Another way to provide service for an Internet port is to let the daemon
2716 program @code{inetd} do the listening. @code{inetd} is a program that
2717 runs all the time and waits (using @code{select}) for messages on a
2718 specified set of ports. When it receives a message, it accepts the
2719 connection (if the socket style calls for connections) and then forks a
2720 child process to run the corresponding server program. You specify the
2721 ports and their programs in the file @file{/etc/inetd.conf}.
2725 * Configuring Inetd::
2729 @subsection @code{inetd} Servers
2731 Writing a server program to be run by @code{inetd} is very simple. Each time
2732 someone requests a connection to the appropriate port, a new server
2733 process starts. The connection already exists at this time; the
2734 socket is available as the standard input descriptor and as the
2735 standard output descriptor (descriptors 0 and 1) in the server
2736 process. So the server program can begin reading and writing data
2737 right away. Often the program needs only the ordinary I/O facilities;
2738 in fact, a general-purpose filter program that knows nothing about
2739 sockets can work as a byte stream server run by @code{inetd}.
2741 You can also use @code{inetd} for servers that use connectionless
2742 communication styles. For these servers, @code{inetd} does not try to accept
2743 a connection, since no connection is possible. It just starts the
2744 server program, which can read the incoming datagram packet from
2745 descriptor 0. The server program can handle one request and then
2746 exit, or you can choose to write it to keep reading more requests
2747 until no more arrive, and then exit. You must specify which of these
2748 two techniques the server uses, when you configure @code{inetd}.
2750 @node Configuring Inetd
2751 @subsection Configuring @code{inetd}
2753 The file @file{/etc/inetd.conf} tells @code{inetd} which ports to listen to
2754 and what server programs to run for them. Normally each entry in the
2755 file is one line, but you can split it onto multiple lines provided
2756 all but the first line of the entry start with whitespace. Lines that
2757 start with @samp{#} are comments.
2759 Here are two standard entries in @file{/etc/inetd.conf}:
2762 ftp stream tcp nowait root /libexec/ftpd ftpd
2763 talk dgram udp wait root /libexec/talkd talkd
2766 An entry has this format:
2769 @var{service} @var{style} @var{protocol} @var{wait} @var{username} @var{program} @var{arguments}
2772 The @var{service} field says which service this program provides. It
2773 should be the name of a service defined in @file{/etc/services}.
2774 @code{inetd} uses @var{service} to decide which port to listen on for
2777 The fields @var{style} and @var{protocol} specify the communication
2778 style and the protocol to use for the listening socket. The style
2779 should be the name of a communication style, converted to lower case
2780 and with @samp{SOCK_} deleted---for example, @samp{stream} or
2781 @samp{dgram}. @var{protocol} should be one of the protocols listed in
2782 @file{/etc/protocols}. The typical protocol names are @samp{tcp} for
2783 byte stream connections and @samp{udp} for unreliable datagrams.
2785 The @var{wait} field should be either @samp{wait} or @samp{nowait}.
2786 Use @samp{wait} if @var{style} is a connectionless style and the
2787 server, once started, handles multiple requests, as many as come in.
2788 Use @samp{nowait} if @code{inetd} should start a new process for each message
2789 or request that comes in. If @var{style} uses connections, then
2790 @var{wait} @strong{must} be @samp{nowait}.
2792 @var{user} is the user name that the server should run as. @code{inetd} runs
2793 as root, so it can set the user ID of its children arbitrarily. It's
2794 best to avoid using @samp{root} for @var{user} if you can; but some
2795 servers, such as Telnet and FTP, read a username and password
2796 themselves. These servers need to be root initially so they can log
2797 in as commanded by the data coming over the network.
2799 @var{program} together with @var{arguments} specifies the command to
2800 run to start the server. @var{program} should be an absolute file
2801 name specifying the executable file to run. @var{arguments} consists
2802 of any number of whitespace-separated words, which become the
2803 command-line arguments of @var{program}. The first word in
2804 @var{arguments} is argument zero, which should by convention be the
2805 program name itself (sans directories).
2807 If you edit @file{/etc/inetd.conf}, you can tell @code{inetd} to reread the
2808 file and obey its new contents by sending the @code{inetd} process the
2809 @code{SIGHUP} signal. You'll have to use @code{ps} to determine the
2810 process ID of the @code{inetd} process, as it is not fixed.
2812 @c !!! could document /etc/inetd.sec
2814 @node Socket Options
2815 @section Socket Options
2816 @cindex socket options
2818 This section describes how to read or set various options that modify
2819 the behavior of sockets and their underlying communications protocols.
2821 @cindex level, for socket options
2822 @cindex socket option level
2823 When you are manipulating a socket option, you must specify which
2824 @dfn{level} the option pertains to. This describes whether the option
2825 applies to the socket interface, or to a lower-level communications
2829 * Socket Option Functions:: The basic functions for setting and getting
2831 * Socket-Level Options:: Details of the options at the socket level.
2834 @node Socket Option Functions
2835 @subsection Socket Option Functions
2837 @pindex sys/socket.h
2838 Here are the functions for examining and modifying socket options.
2839 They are declared in @file{sys/socket.h}.
2841 @comment sys/socket.h
2843 @deftypefun int getsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t *@var{optlen-ptr})
2844 The @code{getsockopt} function gets information about the value of
2845 option @var{optname} at level @var{level} for socket @var{socket}.
2847 The option value is stored in a buffer that @var{optval} points to.
2848 Before the call, you should supply in @code{*@var{optlen-ptr}} the
2849 size of this buffer; on return, it contains the number of bytes of
2850 information actually stored in the buffer.
2852 Most options interpret the @var{optval} buffer as a single @code{int}
2855 The actual return value of @code{getsockopt} is @code{0} on success
2856 and @code{-1} on failure. The following @code{errno} error conditions
2861 The @var{socket} argument is not a valid file descriptor.
2864 The descriptor @var{socket} is not a socket.
2867 The @var{optname} doesn't make sense for the given @var{level}.
2871 @comment sys/socket.h
2873 @deftypefun int setsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t @var{optlen})
2874 This function is used to set the socket option @var{optname} at level
2875 @var{level} for socket @var{socket}. The value of the option is passed
2876 in the buffer @var{optval}, which has size @var{optlen}.
2881 The return value and error codes for @code{setsockopt} are the same as
2882 for @code{getsockopt}.
2885 The return value and error codes for @code{setsockopt} are the same as
2886 for @code{getsockopt}.
2891 @node Socket-Level Options
2892 @subsection Socket-Level Options
2894 @comment sys/socket.h
2896 @deftypevr Constant int SOL_SOCKET
2897 Use this constant as the @var{level} argument to @code{getsockopt} or
2898 @code{setsockopt} to manipulate the socket-level options described in
2902 @pindex sys/socket.h
2904 Here is a table of socket-level option names; all are defined in the
2905 header file @file{sys/socket.h}.
2908 @comment sys/socket.h
2911 @c Extra blank line here makes the table look better.
2913 This option toggles recording of debugging information in the underlying
2914 protocol modules. The value has type @code{int}; a nonzero value means
2916 @c !!! should say how this is used
2917 @c Ok, anyone who knows, please explain.
2919 @comment sys/socket.h
2922 This option controls whether @code{bind} (@pxref{Setting Address})
2923 should permit reuse of local addresses for this socket. If you enable
2924 this option, you can actually have two sockets with the same Internet
2925 port number; but the system won't allow you to use the two
2926 identically-named sockets in a way that would confuse the Internet. The
2927 reason for this option is that some higher-level Internet protocols,
2928 including FTP, require you to keep reusing the same port number.
2930 The value has type @code{int}; a nonzero value means ``yes''.
2932 @comment sys/socket.h
2935 This option controls whether the underlying protocol should
2936 periodically transmit messages on a connected socket. If the peer
2937 fails to respond to these messages, the connection is considered
2938 broken. The value has type @code{int}; a nonzero value means
2941 @comment sys/socket.h
2944 This option controls whether outgoing messages bypass the normal
2945 message routing facilities. If set, messages are sent directly to the
2946 network interface instead. The value has type @code{int}; a nonzero
2947 value means ``yes''.
2949 @comment sys/socket.h
2952 This option specifies what should happen when the socket of a type
2953 that promises reliable delivery still has untransmitted messages when
2954 it is closed; see @ref{Closing a Socket}. The value has type
2955 @code{struct linger}.
2957 @comment sys/socket.h
2959 @deftp {Data Type} {struct linger}
2960 This structure type has the following members:
2964 This field is interpreted as a boolean. If nonzero, @code{close}
2965 blocks until the data is transmitted or the timeout period has expired.
2968 This specifies the timeout period, in seconds.
2972 @comment sys/socket.h
2975 This option controls whether datagrams may be broadcast from the socket.
2976 The value has type @code{int}; a nonzero value means ``yes''.
2978 @comment sys/socket.h
2981 If this option is set, out-of-band data received on the socket is
2982 placed in the normal input queue. This permits it to be read using
2983 @code{read} or @code{recv} without specifying the @code{MSG_OOB}
2984 flag. @xref{Out-of-Band Data}. The value has type @code{int}; a
2985 nonzero value means ``yes''.
2987 @comment sys/socket.h
2990 This option gets or sets the size of the output buffer. The value is a
2991 @code{size_t}, which is the size in bytes.
2993 @comment sys/socket.h
2996 This option gets or sets the size of the input buffer. The value is a
2997 @code{size_t}, which is the size in bytes.
2999 @comment sys/socket.h
3002 @comment sys/socket.h
3005 This option can be used with @code{getsockopt} only. It is used to
3006 get the socket's communication style. @code{SO_TYPE} is the
3007 historical name, and @code{SO_STYLE} is the preferred name in GNU.
3008 The value has type @code{int} and its value designates a communication
3009 style; see @ref{Communication Styles}.
3011 @comment sys/socket.h
3014 @c Extra blank line here makes the table look better.
3016 This option can be used with @code{getsockopt} only. It is used to reset
3017 the error status of the socket. The value is an @code{int}, which represents
3018 the previous error status.
3019 @c !!! what is "socket error status"? this is never defined.
3022 @node Networks Database
3023 @section Networks Database
3024 @cindex networks database
3025 @cindex converting network number to network name
3026 @cindex converting network name to network number
3028 @pindex /etc/networks
3030 Many systems come with a database that records a list of networks known
3031 to the system developer. This is usually kept either in the file
3032 @file{/etc/networks} or in an equivalent from a name server. This data
3033 base is useful for routing programs such as @code{route}, but it is not
3034 useful for programs that simply communicate over the network. We
3035 provide functions to access this data base, which are declared in
3040 @deftp {Data Type} {struct netent}
3041 This data type is used to represent information about entries in the
3042 networks database. It has the following members:
3046 This is the ``official'' name of the network.
3048 @item char **n_aliases
3049 These are alternative names for the network, represented as a vector
3050 of strings. A null pointer terminates the array.
3052 @item int n_addrtype
3053 This is the type of the network number; this is always equal to
3054 @code{AF_INET} for Internet networks.
3056 @item unsigned long int n_net
3057 This is the network number. Network numbers are returned in host
3058 byte order; see @ref{Byte Order}.
3062 Use the @code{getnetbyname} or @code{getnetbyaddr} functions to search
3063 the networks database for information about a specific network. The
3064 information is returned in a statically-allocated structure; you must
3065 copy the information if you need to save it.
3069 @deftypefun {struct netent *} getnetbyname (const char *@var{name})
3070 The @code{getnetbyname} function returns information about the network
3071 named @var{name}. It returns a null pointer if there is no such
3077 @deftypefun {struct netent *} getnetbyaddr (unsigned long int @var{net}, int @var{type})
3078 The @code{getnetbyaddr} function returns information about the network
3079 of type @var{type} with number @var{net}. You should specify a value of
3080 @code{AF_INET} for the @var{type} argument for Internet networks.
3082 @code{getnetbyaddr} returns a null pointer if there is no such
3086 You can also scan the networks database using @code{setnetent},
3087 @code{getnetent}, and @code{endnetent}. Be careful in using these
3088 functions, because they are not reentrant.
3092 @deftypefun void setnetent (int @var{stayopen})
3093 This function opens and rewinds the networks database.
3095 If the @var{stayopen} argument is nonzero, this sets a flag so that
3096 subsequent calls to @code{getnetbyname} or @code{getnetbyaddr} will
3097 not close the database (as they usually would). This makes for more
3098 efficiency if you call those functions several times, by avoiding
3099 reopening the database for each call.
3104 @deftypefun {struct netent *} getnetent (void)
3105 This function returns the next entry in the networks database. It
3106 returns a null pointer if there are no more entries.
3111 @deftypefun void endnetent (void)
3112 This function closes the networks database.