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 now the POSIX people came and unified the interface with their 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 A solution is provided by the Unix98 specification which finally
149 introduces a type @code{socklen_t}. This type is used in all of the
150 cases that were previously changed to use @code{size_t}. The only
151 requirement of this type is that it is an unsigned type of at least 32
152 bits. Therefore, implementations which require references to 32 bit
153 variables be passed can be as happy as implementations which use right
154 from the start 64 bit values.
157 @node Communication Styles
158 @section Communication Styles
160 The GNU library includes support for several different kinds of sockets,
161 each with different characteristics. This section describes the
162 supported socket types. The symbolic constants listed here are
163 defined in @file{sys/socket.h}.
166 @comment sys/socket.h
168 @deftypevr Macro int SOCK_STREAM
169 The @code{SOCK_STREAM} style is like a pipe (@pxref{Pipes and FIFOs});
170 it operates over a connection with a particular remote socket, and
171 transmits data reliably as a stream of bytes.
173 Use of this style is covered in detail in @ref{Connections}.
176 @comment sys/socket.h
178 @deftypevr Macro int SOCK_DGRAM
179 The @code{SOCK_DGRAM} style is used for sending
180 individually-addressed packets, unreliably.
181 It is the diametrical opposite of @code{SOCK_STREAM}.
183 Each time you write data to a socket of this kind, that data becomes
184 one packet. Since @code{SOCK_DGRAM} sockets do not have connections,
185 you must specify the recipient address with each packet.
187 The only guarantee that the system makes about your requests to
188 transmit data is that it will try its best to deliver each packet you
189 send. It may succeed with the sixth packet after failing with the
190 fourth and fifth packets; the seventh packet may arrive before the
191 sixth, and may arrive a second time after the sixth.
193 The typical use for @code{SOCK_DGRAM} is in situations where it is
194 acceptable to simply resend a packet if no response is seen in a
195 reasonable amount of time.
197 @xref{Datagrams}, for detailed information about how to use datagram
202 @c This appears to be only for the NS domain, which we aren't
203 @c discussing and probably won't support either.
204 @comment sys/socket.h
206 @deftypevr Macro int SOCK_SEQPACKET
207 This style is like @code{SOCK_STREAM} except that the data is
208 structured into packets.
210 A program that receives data over a @code{SOCK_SEQPACKET} socket
211 should be prepared to read the entire message packet in a single call
212 to @code{read}; if it only reads part of the message, the remainder of
213 the message is simply discarded instead of being available for
214 subsequent calls to @code{read}.
216 Many protocols do not support this communication style.
221 @comment sys/socket.h
223 @deftypevr Macro int SOCK_RDM
224 This style is a reliable version of @code{SOCK_DGRAM}: it sends
225 individually addressed packets, but guarantees that each packet sent
226 arrives exactly once.
228 @strong{Warning:} It is not clear this is actually supported
229 by any operating system.
233 @comment sys/socket.h
235 @deftypevr Macro int SOCK_RAW
236 This style provides access to low-level network protocols and
237 interfaces. Ordinary user programs usually have no need to use this
241 @node Socket Addresses
242 @section Socket Addresses
244 @cindex address of socket
245 @cindex name of socket
246 @cindex binding a socket address
247 @cindex socket address (name) binding
248 The name of a socket is normally called an @dfn{address}. The
249 functions and symbols for dealing with socket addresses were named
250 inconsistently, sometimes using the term ``name'' and sometimes using
251 ``address''. You can regard these terms as synonymous where sockets
254 A socket newly created with the @code{socket} function has no
255 address. Other processes can find it for communication only if you
256 give it an address. We call this @dfn{binding} the address to the
257 socket, and the way to do it is with the @code{bind} function.
259 You need be concerned with the address of a socket if other processes
260 are to find it and start communicating with it. You can specify an
261 address for other sockets, but this is usually pointless; the first time
262 you send data from a socket, or use it to initiate a connection, the
263 system assigns an address automatically if you have not specified one.
265 Occasionally a client needs to specify an address because the server
266 discriminates based on addresses; for example, the rsh and rlogin
267 protocols look at the client's socket address and only bypass password
268 checking if it is less than @code{IPPORT_RESERVED} (@pxref{Ports}).
270 The details of socket addresses vary depending on what namespace you are
271 using. @xref{Local Namespace}, or @ref{Internet Namespace}, for specific
274 Regardless of the namespace, you use the same functions @code{bind} and
275 @code{getsockname} to set and examine a socket's address. These
276 functions use a phony data type, @code{struct sockaddr *}, to accept the
277 address. In practice, the address lives in a structure of some other
278 data type appropriate to the address format you are using, but you cast
279 its address to @code{struct sockaddr *} when you pass it to
283 * Address Formats:: About @code{struct sockaddr}.
284 * Setting Address:: Binding an address to a socket.
285 * Reading Address:: Reading the address of a socket.
288 @node Address Formats
289 @subsection Address Formats
291 The functions @code{bind} and @code{getsockname} use the generic data
292 type @code{struct sockaddr *} to represent a pointer to a socket
293 address. You can't use this data type effectively to interpret an
294 address or construct one; for that, you must use the proper data type
295 for the socket's namespace.
297 Thus, the usual practice is to construct an address in the proper
298 namespace-specific type, then cast a pointer to @code{struct sockaddr *}
299 when you call @code{bind} or @code{getsockname}.
301 The one piece of information that you can get from the @code{struct
302 sockaddr} data type is the @dfn{address format} designator which tells
303 you which data type to use to understand the address fully.
306 The symbols in this section are defined in the header file
309 @comment sys/socket.h
311 @deftp {Data Type} {struct sockaddr}
312 The @code{struct sockaddr} type itself has the following members:
315 @item short int sa_family
316 This is the code for the address format of this address. It
317 identifies the format of the data which follows.
319 @item char sa_data[14]
320 This is the actual socket address data, which is format-dependent. Its
321 length also depends on the format, and may well be more than 14. The
322 length 14 of @code{sa_data} is essentially arbitrary.
326 Each address format has a symbolic name which starts with @samp{AF_}.
327 Each of them corresponds to a @samp{PF_} symbol which designates the
328 corresponding namespace. Here is a list of address format names:
331 @comment sys/socket.h
335 This designates the address format that goes with the local namespace.
336 (@code{PF_LOCAL} is the name of that namespace.) @xref{Local Namespace
337 Details}, for information about this address format.
339 @comment sys/socket.h
343 This is a synonym for @code{AF_LOCAL}, for compatibility.
344 (@code{PF_UNIX} is likewise a synonym for @code{PF_LOCAL}.)
346 @comment sys/socket.h
350 This is another synonym for @code{AF_LOCAL}, for compatibility.
351 (@code{PF_FILE} is likewise a synonym for @code{PF_LOCAL}.)
353 @comment sys/socket.h
357 This designates the address format that goes with the Internet
358 namespace. (@code{PF_INET} is the name of that namespace.)
359 @xref{Internet Address Formats}.
361 @comment sys/socket.h
362 @comment IPv6 Basic API
364 This is similar to @code{AF_INET}, but refers to the IPv6 protocol.
365 (@code{PF_INET6} is the name of the corresponding namespace.)
367 @comment sys/socket.h
371 This designates no particular address format. It is used only in rare
372 cases, such as to clear out the default destination address of a
373 ``connected'' datagram socket. @xref{Sending Datagrams}.
375 The corresponding namespace designator symbol @code{PF_UNSPEC} exists
376 for completeness, but there is no reason to use it in a program.
379 @file{sys/socket.h} defines symbols starting with @samp{AF_} for many
380 different kinds of networks, all or most of which are not actually
381 implemented. We will document those that really work, as we receive
382 information about how to use them.
384 @node Setting Address
385 @subsection Setting the Address of a Socket
388 Use the @code{bind} function to assign an address to a socket. The
389 prototype for @code{bind} is in the header file @file{sys/socket.h}.
390 For examples of use, see @ref{Local Socket Example}, or see @ref{Inet Example}.
392 @comment sys/socket.h
394 @deftypefun int bind (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
395 The @code{bind} function assigns an address to the socket
396 @var{socket}. The @var{addr} and @var{length} arguments specify the
397 address; the detailed format of the address depends on the namespace.
398 The first part of the address is always the format designator, which
399 specifies a namespace, and says that the address is in the format for
402 The return value is @code{0} on success and @code{-1} on failure. The
403 following @code{errno} error conditions are defined for this function:
407 The @var{socket} argument is not a valid file descriptor.
410 The descriptor @var{socket} is not a socket.
413 The specified address is not available on this machine.
416 Some other socket is already using the specified address.
419 The socket @var{socket} already has an address.
422 You do not have permission to access the requested address. (In the
423 Internet domain, only the super-user is allowed to specify a port number
424 in the range 0 through @code{IPPORT_RESERVED} minus one; see
428 Additional conditions may be possible depending on the particular namespace
432 @node Reading Address
433 @subsection Reading the Address of a Socket
436 Use the function @code{getsockname} to examine the address of an
437 Internet socket. The prototype for this function is in the header file
440 @comment sys/socket.h
442 @deftypefun int getsockname (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
443 The @code{getsockname} function returns information about the
444 address of the socket @var{socket} in the locations specified by the
445 @var{addr} and @var{length-ptr} arguments. Note that the
446 @var{length-ptr} is a pointer; you should initialize it to be the
447 allocation size of @var{addr}, and on return it contains the actual
448 size of the address data.
450 The format of the address data depends on the socket namespace. The
451 length of the information is usually fixed for a given namespace, so
452 normally you can know exactly how much space is needed and can provide
453 that much. The usual practice is to allocate a place for the value
454 using the proper data type for the socket's namespace, then cast its
455 address to @code{struct sockaddr *} to pass it to @code{getsockname}.
457 The return value is @code{0} on success and @code{-1} on error. The
458 following @code{errno} error conditions are defined for this function:
462 The @var{socket} argument is not a valid file descriptor.
465 The descriptor @var{socket} is not a socket.
468 There are not enough internal buffers available for the operation.
472 You can't read the address of a socket in the file namespace. This is
473 consistent with the rest of the system; in general, there's no way to
474 find a file's name from a descriptor for that file.
476 @node Interface Naming
477 @section Interface Naming
479 Each network interface has a name. This usually consists of a few
480 letters that relate to the type of interface, which may be followed by a
481 number if there is more than one interface of that type. Examples
482 might be @code{lo} (the loopback interface) and @code{eth0} (the first
485 Although such names are convenient for humans, it would be clumsy to
486 have to use them whenever a program needs to refer to an interface. In
487 such situations an interface is referred to by its @dfn{index}, which is
488 an arbitrarily-assigned small positive integer.
490 The following functions, constants and data types are declared in the
491 header file @file{net/if.h}.
494 @deftypevr Constant size_t IFNAMSIZ
495 This constant defines the maximum buffer size needed to hold an
496 interface name, including its terminating zero byte.
500 @comment IPv6 basic API
501 @deftypefun {unsigned int} if_nametoindex (const char *ifname)
502 This function yields the interface index corresponding to a particular
503 name. If no interface exists with the name given, it returns 0.
507 @comment IPv6 basic API
508 @deftypefun {char *} if_indextoname (unsigned int ifindex, char *ifname)
509 This function maps an interface index to its corresponding name. The
510 returned name is placed in the buffer pointed to by @code{ifname}, which
511 must be at least @code{IFNAMSIZE} bytes in length. If the index was
512 invalid, the function's return value is a null pointer, otherwise it is
517 @comment IPv6 basic API
518 @deftp {Data Type} {struct if_nameindex}
519 This data type is used to hold the information about a single
520 interface. It has the following members:
523 @item unsigned int if_index;
524 This is the interface index.
527 This is the null-terminated index name.
533 @comment IPv6 basic API
534 @deftypefun {struct if_nameindex *} if_nameindex (void)
535 This function returns an array of @code{if_nameindex} structures, one
536 for every interface that is present. The end of the list is indicated
537 by a structure with an interface of 0 and a null name pointer. If an
538 error occurs, this function returns a null pointer.
540 The returned structure must be freed with @code{if_freenameindex} after
545 @comment IPv6 basic API
546 @deftypefun void if_freenameindex (struct if_nameindex *ptr)
547 This function frees the structure returned by an earlier call to
551 @node Local Namespace
552 @section The Local Namespace
553 @cindex local namespace, for sockets
555 This section describes the details of the local namespace, whose
556 symbolic name (required when you create a socket) is @code{PF_LOCAL}.
557 The local namespace is also known as ``Unix domain sockets''. Another
558 name is file namespace since socket addresses are normally implemented
562 * Concepts: Local Namespace Concepts. What you need to understand.
563 * Details: Local Namespace Details. Address format, symbolic names, etc.
564 * Example: Local Socket Example. Example of creating a socket.
567 @node Local Namespace Concepts
568 @subsection Local Namespace Concepts
570 In the local namespace, socket addresses are file names. You can specify
571 any file name you want as the address of the socket, but you must have
572 write permission on the directory containing it. In order to connect to
573 a socket, you must have read permission for it. It's common to put
574 these files in the @file{/tmp} directory.
576 One peculiarity of the local namespace is that the name is only used when
577 opening the connection; once that is over with, the address is not
578 meaningful and may not exist.
580 Another peculiarity is that you cannot connect to such a socket from
581 another machine--not even if the other machine shares the file system
582 which contains the name of the socket. You can see the socket in a
583 directory listing, but connecting to it never succeeds. Some programs
584 take advantage of this, such as by asking the client to send its own
585 process ID, and using the process IDs to distinguish between clients.
586 However, we recommend you not to use this method in protocols you design,
587 as we might someday permit connections from other machines that mount
588 the same file systems. Instead, send each new client an identifying
589 number if you want it to have one.
591 After you close a socket in the local namespace, you should delete the
592 file name from the file system. Use @code{unlink} or @code{remove} to
593 do this; see @ref{Deleting Files}.
595 The local namespace supports just one protocol for any communication
596 style; it is protocol number @code{0}.
598 @node Local Namespace Details
599 @subsection Details of Local Namespace
602 To create a socket in the local namespace, use the constant
603 @code{PF_LOCAL} as the @var{namespace} argument to @code{socket} or
604 @code{socketpair}. This constant is defined in @file{sys/socket.h}.
606 @comment sys/socket.h
608 @deftypevr Macro int PF_LOCAL
609 This designates the local namespace, in which socket addresses are local
610 names, and its associated family of protocols. @code{PF_Local} is the
611 macro used by Posix.1g.
614 @comment sys/socket.h
616 @deftypevr Macro int PF_UNIX
617 This is a synonym for @code{PF_LOCAL}, for compatibility's sake.
620 @comment sys/socket.h
622 @deftypevr Macro int PF_FILE
623 This is a synonym for @code{PF_LOCAL}, for compatibility's sake.
626 The structure for specifying socket names in the local namespace is
627 defined in the header file @file{sys/un.h}:
632 @deftp {Data Type} {struct sockaddr_un}
633 This structure is used to specify local namespace socket addresses. It has
634 the following members:
637 @item short int sun_family
638 This identifies the address family or format of the socket address.
639 You should store the value @code{AF_LOCAL} to designate the local
640 namespace. @xref{Socket Addresses}.
642 @item char sun_path[108]
643 This is the file name to use.
645 @strong{Incomplete:} Why is 108 a magic number? RMS suggests making
646 this a zero-length array and tweaking the example following to use
647 @code{alloca} to allocate an appropriate amount of storage based on
648 the length of the filename.
652 You should compute the @var{length} parameter for a socket address in
653 the local namespace as the sum of the size of the @code{sun_family}
654 component and the string length (@emph{not} the allocation size!) of
655 the file name string. This can be done using the macro @code{SUN_LEN}:
659 @deftypefn {Macro} int SUN_LEN (@emph{struct sockaddr_un *} @var{ptr})
660 The macro computes the length of socket address in the local namespace.
663 @node Local Socket Example
664 @subsection Example of Local-Namespace Sockets
666 Here is an example showing how to create and name a socket in the local
670 @include mkfsock.c.texi
673 @node Internet Namespace
674 @section The Internet Namespace
675 @cindex Internet namespace, for sockets
677 This section describes the details of the protocols and socket naming
678 conventions used in the Internet namespace.
680 Originaly the Internet namespace used only IP version 4 (IPv4). With
681 the growing number of hosts on the Internet, a new protocol with a
682 larger address space was neccessary: IP version 6 (IPv6). IPv6
683 introduces besides 128bit addresses (IPv4 has 32bit addresses) also
684 other features and will eventually replace IPv4.
686 To create a socket in the IPv4 Internet namespace, use the symbolic name
687 @code{PF_INET} of this namespace as the @var{namespace} argument to
688 @code{socket} or @code{socketpair}. For IPv6 addresses, you need the
689 macro @code{PF_INET6}. These macros are defined in @file{sys/socket.h}.
692 @comment sys/socket.h
694 @deftypevr Macro int PF_INET
695 This designates the IPv4 Internet namespace and associated family of
699 @deftypevr Macro int AF_INET6
700 This designates the IPv6 Internet namespace and associated family of
704 A socket address for the Internet namespace includes the following components:
708 The address of the machine you want to connect to. Internet addresses
709 can be specified in several ways; these are discussed in @ref{Internet
710 Address Formats}, @ref{Host Addresses}, and @ref{Host Names}.
713 A port number for that machine. @xref{Ports}.
716 You must ensure that the address and port number are represented in a
717 canonical format called @dfn{network byte order}. @xref{Byte Order},
718 for information about this.
721 * Internet Address Formats:: How socket addresses are specified in the
723 * Host Addresses:: All about host addresses of internet host.
724 * Protocols Database:: Referring to protocols by name.
725 * Ports:: Internet port numbers.
726 * Services Database:: Ports may have symbolic names.
727 * Byte Order:: Different hosts may use different byte
728 ordering conventions; you need to
729 canonicalize host address and port number.
730 * Inet Example:: Putting it all together.
733 @node Internet Address Formats
734 @subsection Internet Socket Address Formats
736 In the Internet namespace, for both IPv4 (@code{AF_INET}) and IPv6
737 (@code{AF_INET6}), a socket address consists of a host address
738 and a port on that host. In addition, the protocol you choose serves
739 effectively as a part of the address because local port numbers are
740 meaningful only within a particular protocol.
742 The data types for representing socket addresses in the Internet namespace
743 are defined in the header file @file{netinet/in.h}.
746 @comment netinet/in.h
748 @deftp {Data Type} {struct sockaddr_in}
749 This is the data type used to represent socket addresses in the
750 Internet namespace. It has the following members:
753 @item sa_family_t sin_family
754 This identifies the address family or format of the socket address.
755 You should store the value of @code{AF_INET} in this member.
756 @xref{Socket Addresses}.
758 @item struct in_addr sin_addr
759 This is the Internet address of the host machine. @xref{Host
760 Addresses}, and @ref{Host Names}, for how to get a value to store
763 @item unsigned short int sin_port
764 This is the port number. @xref{Ports}.
768 When you call @code{bind} or @code{getsockname}, you should specify
769 @code{sizeof (struct sockaddr_in)} as the @var{length} parameter if
770 you are using an IPv4 Internet namespace socket address.
772 @deftp {Data Type} {struct sockaddr_in6}
773 This is the data type used to represent socket addresses in the IPv6
774 namespace. It has the following members:
777 @item sa_family_t sin6_family
778 This identifies the address family or format of the socket address.
779 You should store the value of @code{AF_INET6} in this member.
780 @xref{Socket Addresses}.
782 @item struct in6_addr sin6_addr
783 This is the IPv6 address of the host machine. @xref{Host
784 Addresses}, and @ref{Host Names}, for how to get a value to store
787 @item uint32_t sin6_flowinfo
788 This is a currently unimplemented field.
790 @item uint16_t sin6_port
791 This is the port number. @xref{Ports}.
797 @subsection Host Addresses
799 Each computer on the Internet has one or more @dfn{Internet addresses},
800 numbers which identify that computer among all those on the Internet.
801 Users typically write IPv4 numeric host addresses as sequences of four
802 numbers, separated by periods, as in @samp{128.52.46.32}, and IPv6
803 numeric host addresses as sequences of up to eight numbers separated by
804 colons, as in @samp{5f03:1200:836f:c100::1}.
806 Each computer also has one or more @dfn{host names}, which are strings
807 of words separated by periods, as in @samp{mescaline.gnu.org}.
809 Programs that let the user specify a host typically accept both numeric
810 addresses and host names. But the program needs a numeric address to
811 open a connection; to use a host name, you must convert it to the
812 numeric address it stands for.
815 * Abstract Host Addresses:: What a host number consists of.
816 * Data type: Host Address Data Type. Data type for a host number.
817 * Functions: Host Address Functions. Functions to operate on them.
818 * Names: Host Names. Translating host names to host numbers.
821 @node Abstract Host Addresses
822 @subsubsection Internet Host Addresses
823 @cindex host address, Internet
824 @cindex Internet host address
827 Each computer on the Internet has one or more Internet addresses,
828 numbers which identify that computer among all those on the Internet.
831 @cindex network number
832 @cindex local network address number
833 An IPv4 Internet host address is a number containing four bytes of data.
834 Historically these are divided into two parts, a @dfn{network number} and a
835 @dfn{local network address number} within that network. In the
836 mid-1990s classless address were introduced which changed the
837 behaviour. Since some functions implicitly expect the old definitions,
838 we first describe the class based network and will then describe
839 classless addresses. IPv6 uses only classless adresses and therefore
840 the following paragraphs don't apply.
842 The class based IPv4 network number consists of the first one, two or
843 three bytes; the rest of the bytes are the local address.
845 IPv4 network numbers are registered with the Network Information Center
846 (NIC), and are divided into three classes---A, B, and C. The local
847 network address numbers of individual machines are registered with the
848 administrator of the particular network.
850 Class A networks have single-byte numbers in the range 0 to 127. There
851 are only a small number of Class A networks, but they can each support a
852 very large number of hosts. Medium-sized Class B networks have two-byte
853 network numbers, with the first byte in the range 128 to 191. Class C
854 networks are the smallest; they have three-byte network numbers, with
855 the first byte in the range 192-255. Thus, the first 1, 2, or 3 bytes
856 of an Internet address specifies a network. The remaining bytes of the
857 Internet address specify the address within that network.
859 The Class A network 0 is reserved for broadcast to all networks. In
860 addition, the host number 0 within each network is reserved for broadcast
861 to all hosts in that network. These uses are obsolete now but out of
862 compatibility reasons you shouldn't use network 0 and host number 0.
864 The Class A network 127 is reserved for loopback; you can always use
865 the Internet address @samp{127.0.0.1} to refer to the host machine.
867 Since a single machine can be a member of multiple networks, it can
868 have multiple Internet host addresses. However, there is never
869 supposed to be more than one machine with the same host address.
871 @c !!! this section could document the IN_CLASS* macros in <netinet/in.h>.
872 @c No, it shouldn't since they're obsolete.
874 @cindex standard dot notation, for Internet addresses
875 @cindex dot notation, for Internet addresses
876 There are four forms of the @dfn{standard numbers-and-dots notation}
877 for Internet addresses:
880 @item @var{a}.@var{b}.@var{c}.@var{d}
881 This specifies all four bytes of the address individually and is the
882 commonly used representation.
884 @item @var{a}.@var{b}.@var{c}
885 The last part of the address, @var{c}, is interpreted as a 2-byte quantity.
886 This is useful for specifying host addresses in a Class B network with
887 network address number @code{@var{a}.@var{b}}.
889 @item @var{a}.@var{b}
890 The last part of the address, @var{b}, is interpreted as a 3-byte quantity.
891 This is useful for specifying host addresses in a Class A network with
892 network address number @var{a}.
895 If only one part is given, this corresponds directly to the host address
899 Within each part of the address, the usual C conventions for specifying
900 the radix apply. In other words, a leading @samp{0x} or @samp{0X} implies
901 hexadecimal radix; a leading @samp{0} implies octal; and otherwise decimal
904 @subsubheading Classless Addresses
906 IPv4 addresses (and IPv6 addresses also) are now considered as
907 classless. The distinction between classes A, B, and C can be ignored.
908 Instead a IPv4 host adddress consists of a 32-bit address and a 32-bit
909 mask. The mask contains bits of 1 for the network part and bits of 0
910 for the host part. The 1-bits are contigous from the leftmost bit, the
911 0-bits are contigous from the rightmost bit so that the netmask can also
912 be written as a prefix length of bits of 1. Classes A, B and C are just
913 special cases of this general rule. For example, class A addresses have
914 a netmask of @samp{255.0.0.0} or a prefix length of 8.
916 Classless IPv4 network addresses are written in numbers-and-dots
917 notation with the prefix length appended and a slash as separator. For
918 example the class A network 10 is written as @samp{10.0.0.0/8}.
920 @subsubheading IPv6 Addresses
922 IPv6 addresses contain 128 bits (IPv4 has 32 bits) of data. A host
923 address is usually written as eight 16-bit hexadecimal numbers that are
924 separated by colons. Two colons are used to abbreviate strings of
925 consecutive zeros. For example the IPv6 loopback address which is
926 @samp{0:0:0:0:0:0:0:1} can be just written as @samp{::1}.
928 @node Host Address Data Type
929 @subsubsection Host Address Data Type
931 IPv4 Internet host addresses are represented in some contexts as integers
932 (type @code{uint32_t}). In other contexts, the integer is
933 packaged inside a structure of type @code{struct in_addr}. It would
934 be better if the usage were made consistent, but it is not hard to extract
935 the integer from the structure or put the integer into a structure.
937 You will find older code that uses @code{unsigned long int} for
938 IPv4 Internet host addresses instead of @code{uint32_t} or @code{struct
939 in_addr}. Historically @code{unsigned long int} was a 32 bit number but
940 with 64 bit machines this has changed. Using @code{unsigned long int}
941 might break the code if it is used on machines where this type doesn't
942 have 32 bits. @code{uint32_t} is specified by Unix98 and guaranteed to have
945 IPv6 Internet host addresses have 128 bits and are packaged inside a
946 structure of type @code{struct in6_addr}.
948 The following basic definitions for Internet addresses are declared in
949 the header file @file{netinet/in.h}:
952 @comment netinet/in.h
954 @deftp {Data Type} {struct in_addr}
955 This data type is used in certain contexts to contain an IPv4 Internet
956 host address. It has just one field, named @code{s_addr}, which records
957 the host address number as an @code{uint32_t}.
960 @comment netinet/in.h
962 @deftypevr Macro {uint32_t} INADDR_LOOPBACK
963 You can use this constant to stand for ``the address of this machine,''
964 instead of finding its actual address. It is the IPv4 Internet address
965 @samp{127.0.0.1}, which is usually called @samp{localhost}. This
966 special constant saves you the trouble of looking up the address of your
967 own machine. Also, the system usually implements @code{INADDR_LOOPBACK}
968 specially, avoiding any network traffic for the case of one machine
972 @comment netinet/in.h
974 @deftypevr Macro {uint32_t} INADDR_ANY
975 You can use this constant to stand for ``any incoming address,'' when
976 binding to an address. @xref{Setting Address}. This is the usual
977 address to give in the @code{sin_addr} member of @w{@code{struct
978 sockaddr_in}} when you want to accept Internet connections.
981 @comment netinet/in.h
983 @deftypevr Macro {uint32_t} INADDR_BROADCAST
984 This constant is the address you use to send a broadcast message.
985 @c !!! broadcast needs further documented
988 @comment netinet/in.h
990 @deftypevr Macro {uint32_t} INADDR_NONE
991 This constant is returned by some functions to indicate an error.
994 @comment netinet/in.h
995 @comment IPv6 basic API
996 @deftp {Data Type} {struct in6_addr}
997 This data type is used to store an IPv6 address. It stores 128 bits of
998 data, which can be accessed (via a union) in a variety of ways.
1001 @comment netinet/in.h
1002 @comment IPv6 basic API
1003 @deftypevr Constant {struct in6_addr} in6addr_loopback
1004 This constant is the IPv6 address @samp{::1}, the loopback address. See
1005 above for a description of what this means. The macro
1006 @code{IN6ADDR_LOOPBACK_INIT} is provided to allow you to initialise your
1007 own variables to this value.
1010 @comment netinet/in.h
1011 @comment IPv6 basic API
1012 @deftypevr Constant {struct in6_addr} in6addr_any
1013 This constant is the IPv6 address @samp{::}, the unspecified address. See
1014 above for a description of what this means. The macro
1015 @code{IN6ADDR_ANY_INIT} is provided to allow you to initialise your
1016 own variables to this value.
1019 @node Host Address Functions
1020 @subsubsection Host Address Functions
1024 These additional functions for manipulating Internet addresses are
1025 declared in the header file @file{arpa/inet.h}. They represent Internet
1026 addresses in network byte order; they represent network numbers and
1027 local-address-within-network numbers in host byte order. @xref{Byte
1028 Order}, for an explanation of network and host byte order.
1030 @comment arpa/inet.h
1032 @deftypefun int inet_aton (const char *@var{name}, struct in_addr *@var{addr})
1033 This function converts the IPv4 Internet host address @var{name}
1034 from the standard numbers-and-dots notation into binary data and stores
1035 it in the @code{struct in_addr} that @var{addr} points to.
1036 @code{inet_aton} returns nonzero if the address is valid, zero if not.
1039 @comment arpa/inet.h
1041 @deftypefun {uint32_t} inet_addr (const char *@var{name})
1042 This function converts the IPv4 Internet host address @var{name} from the
1043 standard numbers-and-dots notation into binary data. If the input is
1044 not valid, @code{inet_addr} returns @code{INADDR_NONE}. This is an
1045 obsolete interface to @code{inet_aton}, described immediately above; it
1046 is obsolete because @code{INADDR_NONE} is a valid address
1047 (255.255.255.255), and @code{inet_aton} provides a cleaner way to
1048 indicate error return.
1051 @comment arpa/inet.h
1053 @deftypefun {uint32_t} inet_network (const char *@var{name})
1054 This function extracts the network number from the address @var{name},
1055 given in the standard numbers-and-dots notation. The returned address is
1056 in host order. If the input is not valid, @code{inet_network} returns
1059 The function works only with traditional IPv4 class A, B and C network
1060 types. It doesn't work with classless addresses and shouldn't be used
1064 @comment arpa/inet.h
1066 @deftypefun {char *} inet_ntoa (struct in_addr @var{addr})
1067 This function converts the IPv4 Internet host address @var{addr} to a
1068 string in the standard numbers-and-dots notation. The return value is
1069 a pointer into a statically-allocated buffer. Subsequent calls will
1070 overwrite the same buffer, so you should copy the string if you need
1073 In multi-threaded programs each thread has an own statically-allocated
1074 buffer. But still subsequent calls of @code{inet_ntoa} in the same
1075 thread will overwrite the result of the last call.
1077 Instead of @code{inet_ntoa} the newer function @code{inet_ntop} which is
1078 described below should be used since it handles both IPv4 and IPv6
1082 @comment arpa/inet.h
1084 @deftypefun {struct in_addr} inet_makeaddr (uint32_t @var{net}, uint32_t @var{local})
1085 This function makes an IPv4 Internet host address by combining the network
1086 number @var{net} with the local-address-within-network number
1090 @comment arpa/inet.h
1092 @deftypefun uint32_t inet_lnaof (struct in_addr @var{addr})
1093 This function returns the local-address-within-network part of the
1094 Internet host address @var{addr}.
1096 The function works only with traditional IPv4 class A, B and C network
1097 types. It doesn't work with classless addresses and shouldn't be used
1101 @comment arpa/inet.h
1103 @deftypefun uint32_t inet_netof (struct in_addr @var{addr})
1104 This function returns the network number part of the Internet host
1107 The function works only with traditional IPv4 class A, B and C network
1108 types. It doesn't work with classless addresses and shouldn't be used
1112 @comment arpa/inet.h
1113 @comment IPv6 basic API
1114 @deftypefun int inet_pton (int @var{af}, const char *@var{cp}, void *@var{buf})
1115 This function converts an Internet address (either IPv4 or IPv6) from
1116 presentation (textual) to network (binary) format. @var{af} should be
1117 either @code{AF_INET} or @code{AF_INET6}, as appropriate for the type of
1118 address being converted. @var{cp} is a pointer to the input string, and
1119 @var{buf} is a pointer to a buffer for the result. It is the caller's
1120 responsibility to make sure the buffer is large enough.
1123 @comment arpa/inet.h
1124 @comment IPv6 basic API
1125 @deftypefun {const char *} inet_ntop (int @var{af}, const void *@var{cp}, char *@var{buf}, size_t @var{len})
1126 This function converts an Internet address (either IPv4 or IPv6) from
1127 network (binary) to presentation (textual) form. @var{af} should be
1128 either @code{AF_INET} or @code{AF_INET6}, as appropriate. @var{cp} is a
1129 pointer to the address to be converted. @var{buf} should be a pointer
1130 to a buffer to hold the result, and @var{len} is the length of this
1131 buffer. The return value from the function will be this buffer address.
1135 @subsubsection Host Names
1136 @cindex hosts database
1137 @cindex converting host name to address
1138 @cindex converting host address to name
1140 Besides the standard numbers-and-dots notation for Internet addresses,
1141 you can also refer to a host by a symbolic name. The advantage of a
1142 symbolic name is that it is usually easier to remember. For example,
1143 the machine with Internet address @samp{158.121.106.19} is also known as
1144 @samp{alpha.gnu.org}; and other machines in the @samp{gnu.org}
1145 domain can refer to it simply as @samp{alpha}.
1149 Internally, the system uses a database to keep track of the mapping
1150 between host names and host numbers. This database is usually either
1151 the file @file{/etc/hosts} or an equivalent provided by a name server.
1152 The functions and other symbols for accessing this database are declared
1153 in @file{netdb.h}. They are BSD features, defined unconditionally if
1154 you include @file{netdb.h}.
1158 @deftp {Data Type} {struct hostent}
1159 This data type is used to represent an entry in the hosts database. It
1160 has the following members:
1164 This is the ``official'' name of the host.
1166 @item char **h_aliases
1167 These are alternative names for the host, represented as a null-terminated
1170 @item int h_addrtype
1171 This is the host address type; in practice, its value is always either
1172 @code{AF_INET} or @code{AF_INET6}, with the latter being used for IPv6
1173 hosts. In principle other kinds of addresses could be represented in
1174 the data base as well as Internet addresses; if this were done, you
1175 might find a value in this field other than @code{AF_INET} or
1176 @code{AF_INET6}. @xref{Socket Addresses}.
1179 This is the length, in bytes, of each address.
1181 @item char **h_addr_list
1182 This is the vector of addresses for the host. (Recall that the host
1183 might be connected to multiple networks and have different addresses on
1184 each one.) The vector is terminated by a null pointer.
1187 This is a synonym for @code{h_addr_list[0]}; in other words, it is the
1192 As far as the host database is concerned, each address is just a block
1193 of memory @code{h_length} bytes long. But in other contexts there is an
1194 implicit assumption that you can convert IPv4 addresses to a
1195 @code{struct in_addr} or an @code{uint32_t}. Host addresses in
1196 a @code{struct hostent} structure are always given in network byte
1197 order; see @ref{Byte Order}.
1199 You can use @code{gethostbyname}, @code{gethostbyname2} or
1200 @code{gethostbyaddr} to search the hosts database for information about
1201 a particular host. The information is returned in a
1202 statically-allocated structure; you must copy the information if you
1203 need to save it across calls. You can also use @code{getaddrinfo} and
1204 @code{getnameinfo} to obtain this information.
1208 @deftypefun {struct hostent *} gethostbyname (const char *@var{name})
1209 The @code{gethostbyname} function returns information about the host
1210 named @var{name}. If the lookup fails, it returns a null pointer.
1214 @comment IPv6 Basic API
1215 @deftypefun {struct hostent *} gethostbyname2 (const char *@var{name}, int @var{af})
1216 The @code{gethostbyname2} function is like @code{gethostbyname}, but
1217 allows the caller to specify the desired address family (e.g.@:
1218 @code{AF_INET} or @code{AF_INET6}) for the result.
1223 @deftypefun {struct hostent *} gethostbyaddr (const char *@var{addr}, int @var{length}, int @var{format})
1224 The @code{gethostbyaddr} function returns information about the host
1225 with Internet address @var{addr}. The parameter @var{addr} is not
1226 really a pointer to char - it can be a pointer to an IPv4 or an IPv6
1227 address. The @var{length} argument is the size (in bytes) of the address
1228 at @var{addr}. @var{format} specifies the address format; for an IPv4
1229 Internet address, specify a value of @code{AF_INET}; for an IPv6
1230 Internet address, use @code{AF_INET6}.
1232 If the lookup fails, @code{gethostbyaddr} returns a null pointer.
1236 If the name lookup by @code{gethostbyname} or @code{gethostbyaddr}
1237 fails, you can find out the reason by looking at the value of the
1238 variable @code{h_errno}. (It would be cleaner design for these
1239 functions to set @code{errno}, but use of @code{h_errno} is compatible
1240 with other systems.) Before using @code{h_errno}, you must declare it
1247 Here are the error codes that you may find in @code{h_errno}:
1252 @item HOST_NOT_FOUND
1253 @vindex HOST_NOT_FOUND
1254 No such host is known in the data base.
1260 This condition happens when the name server could not be contacted. If
1261 you try again later, you may succeed then.
1267 A non-recoverable error occurred.
1273 The host database contains an entry for the name, but it doesn't have an
1274 associated Internet address.
1277 You can also scan the entire hosts database one entry at a time using
1278 @code{sethostent}, @code{gethostent}, and @code{endhostent}. Be careful
1279 in using these functions, because they are not reentrant.
1283 @deftypefun void sethostent (int @var{stayopen})
1284 This function opens the hosts database to begin scanning it. You can
1285 then call @code{gethostent} to read the entries.
1287 @c There was a rumor that this flag has different meaning if using the DNS,
1288 @c but it appears this description is accurate in that case also.
1289 If the @var{stayopen} argument is nonzero, this sets a flag so that
1290 subsequent calls to @code{gethostbyname} or @code{gethostbyaddr} will
1291 not close the database (as they usually would). This makes for more
1292 efficiency if you call those functions several times, by avoiding
1293 reopening the database for each call.
1298 @deftypefun {struct hostent *} gethostent (void)
1299 This function returns the next entry in the hosts database. It
1300 returns a null pointer if there are no more entries.
1305 @deftypefun void endhostent (void)
1306 This function closes the hosts database.
1310 @subsection Internet Ports
1313 A socket address in the Internet namespace consists of a machine's
1314 Internet address plus a @dfn{port number} which distinguishes the
1315 sockets on a given machine (for a given protocol). Port numbers range
1318 Port numbers less than @code{IPPORT_RESERVED} are reserved for standard
1319 servers, such as @code{finger} and @code{telnet}. There is a database
1320 that keeps track of these, and you can use the @code{getservbyname}
1321 function to map a service name onto a port number; see @ref{Services
1324 If you write a server that is not one of the standard ones defined in
1325 the database, you must choose a port number for it. Use a number
1326 greater than @code{IPPORT_USERRESERVED}; such numbers are reserved for
1327 servers and won't ever be generated automatically by the system.
1328 Avoiding conflicts with servers being run by other users is up to you.
1330 When you use a socket without specifying its address, the system
1331 generates a port number for it. This number is between
1332 @code{IPPORT_RESERVED} and @code{IPPORT_USERRESERVED}.
1334 On the Internet, it is actually legitimate to have two different
1335 sockets with the same port number, as long as they never both try to
1336 communicate with the same socket address (host address plus port
1337 number). You shouldn't duplicate a port number except in special
1338 circumstances where a higher-level protocol requires it. Normally,
1339 the system won't let you do it; @code{bind} normally insists on
1340 distinct port numbers. To reuse a port number, you must set the
1341 socket option @code{SO_REUSEADDR}. @xref{Socket-Level Options}.
1343 @pindex netinet/in.h
1344 These macros are defined in the header file @file{netinet/in.h}.
1346 @comment netinet/in.h
1348 @deftypevr Macro int IPPORT_RESERVED
1349 Port numbers less than @code{IPPORT_RESERVED} are reserved for
1353 @comment netinet/in.h
1355 @deftypevr Macro int IPPORT_USERRESERVED
1356 Port numbers greater than or equal to @code{IPPORT_USERRESERVED} are
1357 reserved for explicit use; they will never be allocated automatically.
1360 @node Services Database
1361 @subsection The Services Database
1362 @cindex services database
1363 @cindex converting service name to port number
1364 @cindex converting port number to service name
1366 @pindex /etc/services
1367 The database that keeps track of ``well-known'' services is usually
1368 either the file @file{/etc/services} or an equivalent from a name server.
1369 You can use these utilities, declared in @file{netdb.h}, to access
1370 the services database.
1375 @deftp {Data Type} {struct servent}
1376 This data type holds information about entries from the services database.
1377 It has the following members:
1381 This is the ``official'' name of the service.
1383 @item char **s_aliases
1384 These are alternate names for the service, represented as an array of
1385 strings. A null pointer terminates the array.
1388 This is the port number for the service. Port numbers are given in
1389 network byte order; see @ref{Byte Order}.
1392 This is the name of the protocol to use with this service.
1393 @xref{Protocols Database}.
1397 To get information about a particular service, use the
1398 @code{getservbyname} or @code{getservbyport} functions. The information
1399 is returned in a statically-allocated structure; you must copy the
1400 information if you need to save it across calls.
1404 @deftypefun {struct servent *} getservbyname (const char *@var{name}, const char *@var{proto})
1405 The @code{getservbyname} function returns information about the
1406 service named @var{name} using protocol @var{proto}. If it can't find
1407 such a service, it returns a null pointer.
1409 This function is useful for servers as well as for clients; servers
1410 use it to determine which port they should listen on (@pxref{Listening}).
1415 @deftypefun {struct servent *} getservbyport (int @var{port}, const char *@var{proto})
1416 The @code{getservbyport} function returns information about the
1417 service at port @var{port} using protocol @var{proto}. If it can't
1418 find such a service, it returns a null pointer.
1422 You can also scan the services database using @code{setservent},
1423 @code{getservent}, and @code{endservent}. Be careful in using these
1424 functions, because they are not reentrant.
1428 @deftypefun void setservent (int @var{stayopen})
1429 This function opens the services database to begin scanning it.
1431 If the @var{stayopen} argument is nonzero, this sets a flag so that
1432 subsequent calls to @code{getservbyname} or @code{getservbyport} will
1433 not close the database (as they usually would). This makes for more
1434 efficiency if you call those functions several times, by avoiding
1435 reopening the database for each call.
1440 @deftypefun {struct servent *} getservent (void)
1441 This function returns the next entry in the services database. If
1442 there are no more entries, it returns a null pointer.
1447 @deftypefun void endservent (void)
1448 This function closes the services database.
1452 @subsection Byte Order Conversion
1453 @cindex byte order conversion, for socket
1454 @cindex converting byte order
1457 @cindex little-endian
1458 Different kinds of computers use different conventions for the
1459 ordering of bytes within a word. Some computers put the most
1460 significant byte within a word first (this is called ``big-endian''
1461 order), and others put it last (``little-endian'' order).
1463 @cindex network byte order
1464 So that machines with different byte order conventions can
1465 communicate, the Internet protocols specify a canonical byte order
1466 convention for data transmitted over the network. This is known
1467 as the @dfn{network byte order}.
1469 When establishing an Internet socket connection, you must make sure that
1470 the data in the @code{sin_port} and @code{sin_addr} members of the
1471 @code{sockaddr_in} structure are represented in the network byte order.
1472 If you are encoding integer data in the messages sent through the
1473 socket, you should convert this to network byte order too. If you don't
1474 do this, your program may fail when running on or talking to other kinds
1477 If you use @code{getservbyname} and @code{gethostbyname} or
1478 @code{inet_addr} to get the port number and host address, the values are
1479 already in the network byte order, and you can copy them directly into
1480 the @code{sockaddr_in} structure.
1482 Otherwise, you have to convert the values explicitly. Use @code{htons}
1483 and @code{ntohs} to convert values for the @code{sin_port} member. Use
1484 @code{htonl} and @code{ntohl} to convert IPv4 addresses for the
1485 @code{sin_addr} member. (Remember, @code{struct in_addr} is equivalent
1486 to @code{uint32_t}.) These functions are declared in
1487 @file{netinet/in.h}.
1488 @pindex netinet/in.h
1490 @comment netinet/in.h
1492 @deftypefun {uint16_t} htons (uint16_t @var{hostshort})
1493 This function converts the @code{uint16_t} integer @var{hostshort} from
1494 host byte order to network byte order.
1497 @comment netinet/in.h
1499 @deftypefun {uint16_t} ntohs (uint16_t @var{netshort})
1500 This function converts the @code{uint16_t} integer @var{netshort} from
1501 network byte order to host byte order.
1504 @comment netinet/in.h
1506 @deftypefun {uint32_t} htonl (uint32_t @var{hostlong})
1507 This function converts the @code{uint32_t} integer @var{hostlong} from
1508 host byte order to network byte order.
1510 This is used for IPv4 internet addresses.
1513 @comment netinet/in.h
1515 @deftypefun {uint32_t} ntohl (uint32_t @var{netlong})
1516 This function converts the @code{uint32_t} integer @var{netlong} from
1517 network byte order to host byte order.
1519 This is used for IPv4 internet addresses.
1522 @node Protocols Database
1523 @subsection Protocols Database
1524 @cindex protocols database
1526 The communications protocol used with a socket controls low-level
1527 details of how data is exchanged. For example, the protocol implements
1528 things like checksums to detect errors in transmissions, and routing
1529 instructions for messages. Normal user programs have little reason to
1530 mess with these details directly.
1532 @cindex TCP (Internet protocol)
1533 The default communications protocol for the Internet namespace depends on
1534 the communication style. For stream communication, the default is TCP
1535 (``transmission control protocol''). For datagram communication, the
1536 default is UDP (``user datagram protocol''). For reliable datagram
1537 communication, the default is RDP (``reliable datagram protocol'').
1538 You should nearly always use the default.
1540 @pindex /etc/protocols
1541 Internet protocols are generally specified by a name instead of a
1542 number. The network protocols that a host knows about are stored in a
1543 database. This is usually either derived from the file
1544 @file{/etc/protocols}, or it may be an equivalent provided by a name
1545 server. You look up the protocol number associated with a named
1546 protocol in the database using the @code{getprotobyname} function.
1548 Here are detailed descriptions of the utilities for accessing the
1549 protocols database. These are declared in @file{netdb.h}.
1554 @deftp {Data Type} {struct protoent}
1555 This data type is used to represent entries in the network protocols
1556 database. It has the following members:
1560 This is the official name of the protocol.
1562 @item char **p_aliases
1563 These are alternate names for the protocol, specified as an array of
1564 strings. The last element of the array is a null pointer.
1567 This is the protocol number (in host byte order); use this member as the
1568 @var{protocol} argument to @code{socket}.
1572 You can use @code{getprotobyname} and @code{getprotobynumber} to search
1573 the protocols database for a specific protocol. The information is
1574 returned in a statically-allocated structure; you must copy the
1575 information if you need to save it across calls.
1579 @deftypefun {struct protoent *} getprotobyname (const char *@var{name})
1580 The @code{getprotobyname} function returns information about the
1581 network protocol named @var{name}. If there is no such protocol, it
1582 returns a null pointer.
1587 @deftypefun {struct protoent *} getprotobynumber (int @var{protocol})
1588 The @code{getprotobynumber} function returns information about the
1589 network protocol with number @var{protocol}. If there is no such
1590 protocol, it returns a null pointer.
1593 You can also scan the whole protocols database one protocol at a time by
1594 using @code{setprotoent}, @code{getprotoent}, and @code{endprotoent}.
1595 Be careful in using these functions, because they are not reentrant.
1599 @deftypefun void setprotoent (int @var{stayopen})
1600 This function opens the protocols database to begin scanning it.
1602 If the @var{stayopen} argument is nonzero, this sets a flag so that
1603 subsequent calls to @code{getprotobyname} or @code{getprotobynumber} will
1604 not close the database (as they usually would). This makes for more
1605 efficiency if you call those functions several times, by avoiding
1606 reopening the database for each call.
1611 @deftypefun {struct protoent *} getprotoent (void)
1612 This function returns the next entry in the protocols database. It
1613 returns a null pointer if there are no more entries.
1618 @deftypefun void endprotoent (void)
1619 This function closes the protocols database.
1623 @subsection Internet Socket Example
1625 Here is an example showing how to create and name a socket in the
1626 Internet namespace. The newly created socket exists on the machine that
1627 the program is running on. Rather than finding and using the machine's
1628 Internet address, this example specifies @code{INADDR_ANY} as the host
1629 address; the system replaces that with the machine's actual address.
1632 @include mkisock.c.texi
1635 Here is another example, showing how you can fill in a @code{sockaddr_in}
1636 structure, given a host name string and a port number:
1639 @include isockad.c.texi
1642 @node Misc Namespaces
1643 @section Other Namespaces
1650 Certain other namespaces and associated protocol families are supported
1651 but not documented yet because they are not often used. @code{PF_NS}
1652 refers to the Xerox Network Software protocols. @code{PF_ISO} stands
1653 for Open Systems Interconnect. @code{PF_CCITT} refers to protocols from
1654 CCITT. @file{socket.h} defines these symbols and others naming protocols
1655 not actually implemented.
1657 @code{PF_IMPLINK} is used for communicating between hosts and Internet
1658 Message Processors. For information on this, and on @code{PF_ROUTE}, an
1659 occasionally-used local area routing protocol, see the GNU Hurd Manual
1660 (to appear in the future).
1662 @node Open/Close Sockets
1663 @section Opening and Closing Sockets
1665 This section describes the actual library functions for opening and
1666 closing sockets. The same functions work for all namespaces and
1670 * Creating a Socket:: How to open a socket.
1671 * Closing a Socket:: How to close a socket.
1672 * Socket Pairs:: These are created like pipes.
1675 @node Creating a Socket
1676 @subsection Creating a Socket
1677 @cindex creating a socket
1678 @cindex socket, creating
1679 @cindex opening a socket
1681 The primitive for creating a socket is the @code{socket} function,
1682 declared in @file{sys/socket.h}.
1683 @pindex sys/socket.h
1685 @comment sys/socket.h
1687 @deftypefun int socket (int @var{namespace}, int @var{style}, int @var{protocol})
1688 This function creates a socket and specifies communication style
1689 @var{style}, which should be one of the socket styles listed in
1690 @ref{Communication Styles}. The @var{namespace} argument specifies
1691 the namespace; it must be @code{PF_LOCAL} (@pxref{Local Namespace}) or
1692 @code{PF_INET} (@pxref{Internet Namespace}). @var{protocol}
1693 designates the specific protocol (@pxref{Socket Concepts}); zero is
1694 usually right for @var{protocol}.
1696 The return value from @code{socket} is the file descriptor for the new
1697 socket, or @code{-1} in case of error. The following @code{errno} error
1698 conditions are defined for this function:
1701 @item EPROTONOSUPPORT
1702 The @var{protocol} or @var{style} is not supported by the
1703 @var{namespace} specified.
1706 The process already has too many file descriptors open.
1709 The system already has too many file descriptors open.
1712 The process does not have privilege to create a socket of the specified
1713 @var{style} or @var{protocol}.
1716 The system ran out of internal buffer space.
1719 The file descriptor returned by the @code{socket} function supports both
1720 read and write operations. But, like pipes, sockets do not support file
1721 positioning operations.
1724 For examples of how to call the @code{socket} function,
1725 see @ref{Local Socket Example}, or @ref{Inet Example}.
1728 @node Closing a Socket
1729 @subsection Closing a Socket
1730 @cindex socket, closing
1731 @cindex closing a socket
1732 @cindex shutting down a socket
1733 @cindex socket shutdown
1735 When you are finished using a socket, you can simply close its
1736 file descriptor with @code{close}; see @ref{Opening and Closing Files}.
1737 If there is still data waiting to be transmitted over the connection,
1738 normally @code{close} tries to complete this transmission. You
1739 can control this behavior using the @code{SO_LINGER} socket option to
1740 specify a timeout period; see @ref{Socket Options}.
1742 @pindex sys/socket.h
1743 You can also shut down only reception or only transmission on a
1744 connection by calling @code{shutdown}, which is declared in
1745 @file{sys/socket.h}.
1747 @comment sys/socket.h
1749 @deftypefun int shutdown (int @var{socket}, int @var{how})
1750 The @code{shutdown} function shuts down the connection of socket
1751 @var{socket}. The argument @var{how} specifies what action to
1756 Stop receiving data for this socket. If further data arrives,
1760 Stop trying to transmit data from this socket. Discard any data
1761 waiting to be sent. Stop looking for acknowledgement of data already
1762 sent; don't retransmit it if it is lost.
1765 Stop both reception and transmission.
1768 The return value is @code{0} on success and @code{-1} on failure. The
1769 following @code{errno} error conditions are defined for this function:
1773 @var{socket} is not a valid file descriptor.
1776 @var{socket} is not a socket.
1779 @var{socket} is not connected.
1784 @subsection Socket Pairs
1785 @cindex creating a socket pair
1787 @cindex opening a socket pair
1789 @pindex sys/socket.h
1790 A @dfn{socket pair} consists of a pair of connected (but unnamed)
1791 sockets. It is very similar to a pipe and is used in much the same
1792 way. Socket pairs are created with the @code{socketpair} function,
1793 declared in @file{sys/socket.h}. A socket pair is much like a pipe; the
1794 main difference is that the socket pair is bidirectional, whereas the
1795 pipe has one input-only end and one output-only end (@pxref{Pipes and
1798 @comment sys/socket.h
1800 @deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})
1801 This function creates a socket pair, returning the file descriptors in
1802 @code{@var{filedes}[0]} and @code{@var{filedes}[1]}. The socket pair
1803 is a full-duplex communications channel, so that both reading and writing
1804 may be performed at either end.
1806 The @var{namespace}, @var{style}, and @var{protocol} arguments are
1807 interpreted as for the @code{socket} function. @var{style} should be
1808 one of the communication styles listed in @ref{Communication Styles}.
1809 The @var{namespace} argument specifies the namespace, which must be
1810 @code{AF_LOCAL} (@pxref{Local Namespace}); @var{protocol} specifies the
1811 communications protocol, but zero is the only meaningful value.
1813 If @var{style} specifies a connectionless communication style, then
1814 the two sockets you get are not @emph{connected}, strictly speaking,
1815 but each of them knows the other as the default destination address,
1816 so they can send packets to each other.
1818 The @code{socketpair} function returns @code{0} on success and @code{-1}
1819 on failure. The following @code{errno} error conditions are defined
1824 The process has too many file descriptors open.
1827 The specified namespace is not supported.
1829 @item EPROTONOSUPPORT
1830 The specified protocol is not supported.
1833 The specified protocol does not support the creation of socket pairs.
1838 @section Using Sockets with Connections
1843 The most common communication styles involve making a connection to a
1844 particular other socket, and then exchanging data with that socket
1845 over and over. Making a connection is asymmetric; one side (the
1846 @dfn{client}) acts to request a connection, while the other side (the
1847 @dfn{server}) makes a socket and waits for the connection request.
1852 @ref{Connecting}, describes what the client program must do to
1853 initiate a connection with a server.
1856 @ref{Listening}, and @ref{Accepting Connections}, describe what the
1857 server program must do to wait for and act upon connection requests
1861 @ref{Transferring Data}, describes how data is transferred through the
1867 * Connecting:: What the client program must do.
1868 * Listening:: How a server program waits for requests.
1869 * Accepting Connections:: What the server does when it gets a request.
1870 * Who is Connected:: Getting the address of the
1871 other side of a connection.
1872 * Transferring Data:: How to send and receive data.
1873 * Byte Stream Example:: An example program: a client for communicating
1874 over a byte stream socket in the Internet namespace.
1875 * Server Example:: A corresponding server program.
1876 * Out-of-Band Data:: This is an advanced feature.
1880 @subsection Making a Connection
1881 @cindex connecting a socket
1882 @cindex socket, connecting
1883 @cindex socket, initiating a connection
1884 @cindex socket, client actions
1886 In making a connection, the client makes a connection while the server
1887 waits for and accepts the connection. Here we discuss what the client
1888 program must do, using the @code{connect} function, which is declared in
1889 @file{sys/socket.h}.
1891 @comment sys/socket.h
1893 @deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
1894 The @code{connect} function initiates a connection from the socket
1895 with file descriptor @var{socket} to the socket whose address is
1896 specified by the @var{addr} and @var{length} arguments. (This socket
1897 is typically on another machine, and it must be already set up as a
1898 server.) @xref{Socket Addresses}, for information about how these
1899 arguments are interpreted.
1901 Normally, @code{connect} waits until the server responds to the request
1902 before it returns. You can set nonblocking mode on the socket
1903 @var{socket} to make @code{connect} return immediately without waiting
1904 for the response. @xref{File Status Flags}, for information about
1906 @c !!! how do you tell when it has finished connecting? I suspect the
1907 @c way you do it is select for writing.
1909 The normal return value from @code{connect} is @code{0}. If an error
1910 occurs, @code{connect} returns @code{-1}. The following @code{errno}
1911 error conditions are defined for this function:
1915 The socket @var{socket} is not a valid file descriptor.
1918 File descriptor @var{socket} is not a socket.
1921 The specified address is not available on the remote machine.
1924 The namespace of the @var{addr} is not supported by this socket.
1927 The socket @var{socket} is already connected.
1930 The attempt to establish the connection timed out.
1933 The server has actively refused to establish the connection.
1936 The network of the given @var{addr} isn't reachable from this host.
1939 The socket address of the given @var{addr} is already in use.
1942 The socket @var{socket} is non-blocking and the connection could not be
1943 established immediately. You can determine when the connection is
1944 completely established with @code{select}; @pxref{Waiting for I/O}.
1945 Another @code{connect} call on the same socket, before the connection is
1946 completely established, will fail with @code{EALREADY}.
1949 The socket @var{socket} is non-blocking and already has a pending
1950 connection in progress (see @code{EINPROGRESS} above).
1953 This function is defined as a cancelation point in multi-threaded
1954 programs. So one has to be prepared for this and make sure that
1955 possibly allocated resources (like memory, files descriptors,
1956 semaphores or whatever) are freed even if the thread is canceled.
1957 @c @xref{pthread_cleanup_push}, for a method how to do this.
1961 @subsection Listening for Connections
1962 @cindex listening (sockets)
1963 @cindex sockets, server actions
1964 @cindex sockets, listening
1966 Now let us consider what the server process must do to accept
1967 connections on a socket. First it must use the @code{listen} function
1968 to enable connection requests on the socket, and then accept each
1969 incoming connection with a call to @code{accept} (@pxref{Accepting
1970 Connections}). Once connection requests are enabled on a server socket,
1971 the @code{select} function reports when the socket has a connection
1972 ready to be accepted (@pxref{Waiting for I/O}).
1974 The @code{listen} function is not allowed for sockets using
1975 connectionless communication styles.
1977 You can write a network server that does not even start running until a
1978 connection to it is requested. @xref{Inetd Servers}.
1980 In the Internet namespace, there are no special protection mechanisms
1981 for controlling access to connect to a port; any process on any machine
1982 can make a connection to your server. If you want to restrict access to
1983 your server, make it examine the addresses associated with connection
1984 requests or implement some other handshaking or identification
1987 In the local namespace, the ordinary file protection bits control who has
1988 access to connect to the socket.
1990 @comment sys/socket.h
1992 @deftypefun int listen (int @var{socket}, unsigned int @var{n})
1993 The @code{listen} function enables the socket @var{socket} to accept
1994 connections, thus making it a server socket.
1996 The argument @var{n} specifies the length of the queue for pending
1997 connections. When the queue fills, new clients attempting to connect
1998 fail with @code{ECONNREFUSED} until the server calls @code{accept} to
1999 accept a connection from the queue.
2001 The @code{listen} function returns @code{0} on success and @code{-1}
2002 on failure. The following @code{errno} error conditions are defined
2007 The argument @var{socket} is not a valid file descriptor.
2010 The argument @var{socket} is not a socket.
2013 The socket @var{socket} does not support this operation.
2017 @node Accepting Connections
2018 @subsection Accepting Connections
2019 @cindex sockets, accepting connections
2020 @cindex accepting connections
2022 When a server receives a connection request, it can complete the
2023 connection by accepting the request. Use the function @code{accept}
2026 A socket that has been established as a server can accept connection
2027 requests from multiple clients. The server's original socket
2028 @emph{does not become part} of the connection; instead, @code{accept}
2029 makes a new socket which participates in the connection.
2030 @code{accept} returns the descriptor for this socket. The server's
2031 original socket remains available for listening for further connection
2034 The number of pending connection requests on a server socket is finite.
2035 If connection requests arrive from clients faster than the server can
2036 act upon them, the queue can fill up and additional requests are refused
2037 with a @code{ECONNREFUSED} error. You can specify the maximum length of
2038 this queue as an argument to the @code{listen} function, although the
2039 system may also impose its own internal limit on the length of this
2042 @comment sys/socket.h
2044 @deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length_ptr})
2045 This function is used to accept a connection request on the server
2046 socket @var{socket}.
2048 The @code{accept} function waits if there are no connections pending,
2049 unless the socket @var{socket} has nonblocking mode set. (You can use
2050 @code{select} to wait for a pending connection, with a nonblocking
2051 socket.) @xref{File Status Flags}, for information about nonblocking
2054 The @var{addr} and @var{length-ptr} arguments are used to return
2055 information about the name of the client socket that initiated the
2056 connection. @xref{Socket Addresses}, for information about the format
2059 Accepting a connection does not make @var{socket} part of the
2060 connection. Instead, it creates a new socket which becomes
2061 connected. The normal return value of @code{accept} is the file
2062 descriptor for the new socket.
2064 After @code{accept}, the original socket @var{socket} remains open and
2065 unconnected, and continues listening until you close it. You can
2066 accept further connections with @var{socket} by calling @code{accept}
2069 If an error occurs, @code{accept} returns @code{-1}. The following
2070 @code{errno} error conditions are defined for this function:
2074 The @var{socket} argument is not a valid file descriptor.
2077 The descriptor @var{socket} argument is not a socket.
2080 The descriptor @var{socket} does not support this operation.
2083 @var{socket} has nonblocking mode set, and there are no pending
2084 connections immediately available.
2087 This function is defined as a cancelation point in multi-threaded
2088 programs. So one has to be prepared for this and make sure that
2089 possibly allocated resources (like memory, files descriptors,
2090 semaphores or whatever) are freed even if the thread is canceled.
2091 @c @xref{pthread_cleanup_push}, for a method how to do this.
2094 The @code{accept} function is not allowed for sockets using
2095 connectionless communication styles.
2097 @node Who is Connected
2098 @subsection Who is Connected to Me?
2100 @comment sys/socket.h
2102 @deftypefun int getpeername (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
2103 The @code{getpeername} function returns the address of the socket that
2104 @var{socket} is connected to; it stores the address in the memory space
2105 specified by @var{addr} and @var{length-ptr}. It stores the length of
2106 the address in @code{*@var{length-ptr}}.
2108 @xref{Socket Addresses}, for information about the format of the
2109 address. In some operating systems, @code{getpeername} works only for
2110 sockets in the Internet domain.
2112 The return value is @code{0} on success and @code{-1} on error. The
2113 following @code{errno} error conditions are defined for this function:
2117 The argument @var{socket} is not a valid file descriptor.
2120 The descriptor @var{socket} is not a socket.
2123 The socket @var{socket} is not connected.
2126 There are not enough internal buffers available.
2131 @node Transferring Data
2132 @subsection Transferring Data
2133 @cindex reading from a socket
2134 @cindex writing to a socket
2136 Once a socket has been connected to a peer, you can use the ordinary
2137 @code{read} and @code{write} operations (@pxref{I/O Primitives}) to
2138 transfer data. A socket is a two-way communications channel, so read
2139 and write operations can be performed at either end.
2141 There are also some I/O modes that are specific to socket operations.
2142 In order to specify these modes, you must use the @code{recv} and
2143 @code{send} functions instead of the more generic @code{read} and
2144 @code{write} functions. The @code{recv} and @code{send} functions take
2145 an additional argument which you can use to specify various flags to
2146 control the special I/O modes. For example, you can specify the
2147 @code{MSG_OOB} flag to read or write out-of-band data, the
2148 @code{MSG_PEEK} flag to peek at input, or the @code{MSG_DONTROUTE} flag
2149 to control inclusion of routing information on output.
2152 * Sending Data:: Sending data with @code{send}.
2153 * Receiving Data:: Reading data with @code{recv}.
2154 * Socket Data Options:: Using @code{send} and @code{recv}.
2158 @subsubsection Sending Data
2160 @pindex sys/socket.h
2161 The @code{send} function is declared in the header file
2162 @file{sys/socket.h}. If your @var{flags} argument is zero, you can just
2163 as well use @code{write} instead of @code{send}; see @ref{I/O
2164 Primitives}. If the socket was connected but the connection has broken,
2165 you get a @code{SIGPIPE} signal for any use of @code{send} or
2166 @code{write} (@pxref{Miscellaneous Signals}).
2168 @comment sys/socket.h
2170 @deftypefun int send (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2171 The @code{send} function is like @code{write}, but with the additional
2172 flags @var{flags}. The possible values of @var{flags} are described
2173 in @ref{Socket Data Options}.
2175 This function returns the number of bytes transmitted, or @code{-1} on
2176 failure. If the socket is nonblocking, then @code{send} (like
2177 @code{write}) can return after sending just part of the data.
2178 @xref{File Status Flags}, for information about nonblocking mode.
2180 Note, however, that a successful return value merely indicates that
2181 the message has been sent without error, not necessarily that it has
2182 been received without error.
2184 The following @code{errno} error conditions are defined for this function:
2188 The @var{socket} argument is not a valid file descriptor.
2191 The operation was interrupted by a signal before any data was sent.
2192 @xref{Interrupted Primitives}.
2195 The descriptor @var{socket} is not a socket.
2198 The socket type requires that the message be sent atomically, but the
2199 message is too large for this to be possible.
2202 Nonblocking mode has been set on the socket, and the write operation
2203 would block. (Normally @code{send} blocks until the operation can be
2207 There is not enough internal buffer space available.
2210 You never connected this socket.
2213 This socket was connected but the connection is now broken. In this
2214 case, @code{send} generates a @code{SIGPIPE} signal first; if that
2215 signal is ignored or blocked, or if its handler returns, then
2216 @code{send} fails with @code{EPIPE}.
2219 This function is defined as a cancelation point in multi-threaded
2220 programs. So one has to be prepared for this and make sure that
2221 possibly allocated resources (like memory, files descriptors,
2222 semaphores or whatever) are freed even if the thread is canceled.
2223 @c @xref{pthread_cleanup_push}, for a method how to do this.
2226 @node Receiving Data
2227 @subsubsection Receiving Data
2229 @pindex sys/socket.h
2230 The @code{recv} function is declared in the header file
2231 @file{sys/socket.h}. If your @var{flags} argument is zero, you can
2232 just as well use @code{read} instead of @code{recv}; see @ref{I/O
2235 @comment sys/socket.h
2237 @deftypefun int recv (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2238 The @code{recv} function is like @code{read}, but with the additional
2239 flags @var{flags}. The possible values of @var{flags} are described
2240 in @ref{Socket Data Options}.
2242 If nonblocking mode is set for @var{socket}, and no data is available to
2243 be read, @code{recv} fails immediately rather than waiting. @xref{File
2244 Status Flags}, for information about nonblocking mode.
2246 This function returns the number of bytes received, or @code{-1} on failure.
2247 The following @code{errno} error conditions are defined for this function:
2251 The @var{socket} argument is not a valid file descriptor.
2254 The descriptor @var{socket} is not a socket.
2257 Nonblocking mode has been set on the socket, and the read operation
2258 would block. (Normally, @code{recv} blocks until there is input
2259 available to be read.)
2262 The operation was interrupted by a signal before any data was read.
2263 @xref{Interrupted Primitives}.
2266 You never connected this socket.
2269 This function is defined as a cancelation point in multi-threaded
2270 programs. So one has to be prepared for this and make sure that
2271 possibly allocated resources (like memory, files descriptors,
2272 semaphores or whatever) are freed even if the thread is canceled.
2273 @c @xref{pthread_cleanup_push}, for a method how to do this.
2276 @node Socket Data Options
2277 @subsubsection Socket Data Options
2279 @pindex sys/socket.h
2280 The @var{flags} argument to @code{send} and @code{recv} is a bit
2281 mask. You can bitwise-OR the values of the following macros together
2282 to obtain a value for this argument. All are defined in the header
2283 file @file{sys/socket.h}.
2285 @comment sys/socket.h
2287 @deftypevr Macro int MSG_OOB
2288 Send or receive out-of-band data. @xref{Out-of-Band Data}.
2291 @comment sys/socket.h
2293 @deftypevr Macro int MSG_PEEK
2294 Look at the data but don't remove it from the input queue. This is
2295 only meaningful with input functions such as @code{recv}, not with
2299 @comment sys/socket.h
2301 @deftypevr Macro int MSG_DONTROUTE
2302 Don't include routing information in the message. This is only
2303 meaningful with output operations, and is usually only of interest for
2304 diagnostic or routing programs. We don't try to explain it here.
2307 @node Byte Stream Example
2308 @subsection Byte Stream Socket Example
2310 Here is an example client program that makes a connection for a byte
2311 stream socket in the Internet namespace. It doesn't do anything
2312 particularly interesting once it has connected to the server; it just
2313 sends a text string to the server and exits.
2315 This program uses @code{init_sockaddr} to set up the socket address; see
2319 @include inetcli.c.texi
2322 @node Server Example
2323 @subsection Byte Stream Connection Server Example
2325 The server end is much more complicated. Since we want to allow
2326 multiple clients to be connected to the server at the same time, it
2327 would be incorrect to wait for input from a single client by simply
2328 calling @code{read} or @code{recv}. Instead, the right thing to do is
2329 to use @code{select} (@pxref{Waiting for I/O}) to wait for input on
2330 all of the open sockets. This also allows the server to deal with
2331 additional connection requests.
2333 This particular server doesn't do anything interesting once it has
2334 gotten a message from a client. It does close the socket for that
2335 client when it detects an end-of-file condition (resulting from the
2336 client shutting down its end of the connection).
2338 This program uses @code{make_socket} to set up the socket address; see
2342 @include inetsrv.c.texi
2345 @node Out-of-Band Data
2346 @subsection Out-of-Band Data
2348 @cindex out-of-band data
2349 @cindex high-priority data
2350 Streams with connections permit @dfn{out-of-band} data that is
2351 delivered with higher priority than ordinary data. Typically the
2352 reason for sending out-of-band data is to send notice of an
2353 exceptional condition. The way to send out-of-band data is using
2354 @code{send}, specifying the flag @code{MSG_OOB} (@pxref{Sending
2357 Out-of-band data is received with higher priority because the
2358 receiving process need not read it in sequence; to read the next
2359 available out-of-band data, use @code{recv} with the @code{MSG_OOB}
2360 flag (@pxref{Receiving Data}). Ordinary read operations do not read
2361 out-of-band data; they read only the ordinary data.
2363 @cindex urgent socket condition
2364 When a socket finds that out-of-band data is on its way, it sends a
2365 @code{SIGURG} signal to the owner process or process group of the
2366 socket. You can specify the owner using the @code{F_SETOWN} command
2367 to the @code{fcntl} function; see @ref{Interrupt Input}. You must
2368 also establish a handler for this signal, as described in @ref{Signal
2369 Handling}, in order to take appropriate action such as reading the
2372 Alternatively, you can test for pending out-of-band data, or wait
2373 until there is out-of-band data, using the @code{select} function; it
2374 can wait for an exceptional condition on the socket. @xref{Waiting
2375 for I/O}, for more information about @code{select}.
2377 Notification of out-of-band data (whether with @code{SIGURG} or with
2378 @code{select}) indicates that out-of-band data is on the way; the data
2379 may not actually arrive until later. If you try to read the
2380 out-of-band data before it arrives, @code{recv} fails with an
2381 @code{EWOULDBLOCK} error.
2383 Sending out-of-band data automatically places a ``mark'' in the stream
2384 of ordinary data, showing where in the sequence the out-of-band data
2385 ``would have been''. This is useful when the meaning of out-of-band
2386 data is ``cancel everything sent so far''. Here is how you can test,
2387 in the receiving process, whether any ordinary data was sent before
2391 success = ioctl (socket, SIOCATMARK, &atmark);
2394 The @code{integer} variable @var{atmark} is set to a nonzero value if
2395 the socket's read pointer has reached the ``mark''.
2397 @c Posix 1.g specifies sockatmark for this ioctl. sockatmark is not
2400 Here's a function to discard any ordinary data preceding the
2405 discard_until_mark (int socket)
2409 /* @r{This is not an arbitrary limit; any size will do.} */
2411 int atmark, success;
2413 /* @r{If we have reached the mark, return.} */
2414 success = ioctl (socket, SIOCATMARK, &atmark);
2420 /* @r{Otherwise, read a bunch of ordinary data and discard it.}
2421 @r{This is guaranteed not to read past the mark}
2422 @r{if it starts before the mark.} */
2423 success = read (socket, buffer, sizeof buffer);
2430 If you don't want to discard the ordinary data preceding the mark, you
2431 may need to read some of it anyway, to make room in internal system
2432 buffers for the out-of-band data. If you try to read out-of-band data
2433 and get an @code{EWOULDBLOCK} error, try reading some ordinary data
2434 (saving it so that you can use it when you want it) and see if that
2435 makes room. Here is an example:
2442 struct buffer *next;
2445 /* @r{Read the out-of-band data from SOCKET and return it}
2446 @r{as a `struct buffer', which records the address of the data}
2449 @r{It may be necessary to read some ordinary data}
2450 @r{in order to make room for the out-of-band data.}
2451 @r{If so, the ordinary data is saved as a chain of buffers}
2452 @r{found in the `next' field of the value.} */
2455 read_oob (int socket)
2457 struct buffer *tail = 0;
2458 struct buffer *list = 0;
2462 /* @r{This is an arbitrary limit.}
2463 @r{Does anyone know how to do this without a limit?} */
2464 char *buffer = (char *) xmalloc (1024);
2468 /* @r{Try again to read the out-of-band data.} */
2469 success = recv (socket, buffer, sizeof buffer, MSG_OOB);
2472 /* @r{We got it, so return it.} */
2474 = (struct buffer *) xmalloc (sizeof (struct buffer));
2475 link->buffer = buffer;
2476 link->size = success;
2481 /* @r{If we fail, see if we are at the mark.} */
2482 success = ioctl (socket, SIOCATMARK, &atmark);
2487 /* @r{At the mark; skipping past more ordinary data cannot help.}
2488 @r{So just wait a while.} */
2493 /* @r{Otherwise, read a bunch of ordinary data and save it.}
2494 @r{This is guaranteed not to read past the mark}
2495 @r{if it starts before the mark.} */
2496 success = read (socket, buffer, sizeof buffer);
2500 /* @r{Save this data in the buffer list.} */
2503 = (struct buffer *) xmalloc (sizeof (struct buffer));
2504 link->buffer = buffer;
2505 link->size = success;
2507 /* @r{Add the new link to the end of the list.} */
2519 @section Datagram Socket Operations
2521 @cindex datagram socket
2522 This section describes how to use communication styles that don't use
2523 connections (styles @code{SOCK_DGRAM} and @code{SOCK_RDM}). Using
2524 these styles, you group data into packets and each packet is an
2525 independent communication. You specify the destination for each
2526 packet individually.
2528 Datagram packets are like letters: you send each one independently,
2529 with its own destination address, and they may arrive in the wrong
2530 order or not at all.
2532 The @code{listen} and @code{accept} functions are not allowed for
2533 sockets using connectionless communication styles.
2536 * Sending Datagrams:: Sending packets on a datagram socket.
2537 * Receiving Datagrams:: Receiving packets on a datagram socket.
2538 * Datagram Example:: An example program: packets sent over a
2539 datagram socket in the local namespace.
2540 * Example Receiver:: Another program, that receives those packets.
2543 @node Sending Datagrams
2544 @subsection Sending Datagrams
2545 @cindex sending a datagram
2546 @cindex transmitting datagrams
2547 @cindex datagrams, transmitting
2549 @pindex sys/socket.h
2550 The normal way of sending data on a datagram socket is by using the
2551 @code{sendto} function, declared in @file{sys/socket.h}.
2553 You can call @code{connect} on a datagram socket, but this only
2554 specifies a default destination for further data transmission on the
2555 socket. When a socket has a default destination, then you can use
2556 @code{send} (@pxref{Sending Data}) or even @code{write} (@pxref{I/O
2557 Primitives}) to send a packet there. You can cancel the default
2558 destination by calling @code{connect} using an address format of
2559 @code{AF_UNSPEC} in the @var{addr} argument. @xref{Connecting}, for
2560 more information about the @code{connect} function.
2562 @comment sys/socket.h
2564 @deftypefun int sendto (int @var{socket}, void *@var{buffer}. size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, socklen_t @var{length})
2565 The @code{sendto} function transmits the data in the @var{buffer}
2566 through the socket @var{socket} to the destination address specified
2567 by the @var{addr} and @var{length} arguments. The @var{size} argument
2568 specifies the number of bytes to be transmitted.
2570 The @var{flags} are interpreted the same way as for @code{send}; see
2571 @ref{Socket Data Options}.
2573 The return value and error conditions are also the same as for
2574 @code{send}, but you cannot rely on the system to detect errors and
2575 report them; the most common error is that the packet is lost or there
2576 is no one at the specified address to receive it, and the operating
2577 system on your machine usually does not know this.
2579 It is also possible for one call to @code{sendto} to report an error
2580 due to a problem related to a previous call.
2582 This function is defined as a cancelation point in multi-threaded
2583 programs. So one has to be prepared for this and make sure that
2584 possibly allocated resources (like memory, files descriptors,
2585 semaphores or whatever) are freed even if the thread is canceled.
2586 @c @xref{pthread_cleanup_push}, for a method how to do this.
2589 @node Receiving Datagrams
2590 @subsection Receiving Datagrams
2591 @cindex receiving datagrams
2593 The @code{recvfrom} function reads a packet from a datagram socket and
2594 also tells you where it was sent from. This function is declared in
2595 @file{sys/socket.h}.
2597 @comment sys/socket.h
2599 @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})
2600 The @code{recvfrom} function reads one packet from the socket
2601 @var{socket} into the buffer @var{buffer}. The @var{size} argument
2602 specifies the maximum number of bytes to be read.
2604 If the packet is longer than @var{size} bytes, then you get the first
2605 @var{size} bytes of the packet, and the rest of the packet is lost.
2606 There's no way to read the rest of the packet. Thus, when you use a
2607 packet protocol, you must always know how long a packet to expect.
2609 The @var{addr} and @var{length-ptr} arguments are used to return the
2610 address where the packet came from. @xref{Socket Addresses}. For a
2611 socket in the local domain, the address information won't be meaningful,
2612 since you can't read the address of such a socket (@pxref{Local
2613 Namespace}). You can specify a null pointer as the @var{addr} argument
2614 if you are not interested in this information.
2616 The @var{flags} are interpreted the same way as for @code{recv}
2617 (@pxref{Socket Data Options}). The return value and error conditions
2618 are also the same as for @code{recv}.
2620 This function is defined as a cancelation point in multi-threaded
2621 programs. So one has to be prepared for this and make sure that
2622 possibly allocated resources (like memory, files descriptors,
2623 semaphores or whatever) are freed even if the thread is canceled.
2624 @c @xref{pthread_cleanup_push}, for a method how to do this.
2627 You can use plain @code{recv} (@pxref{Receiving Data}) instead of
2628 @code{recvfrom} if you know don't need to find out who sent the packet
2629 (either because you know where it should come from or because you
2630 treat all possible senders alike). Even @code{read} can be used if
2631 you don't want to specify @var{flags} (@pxref{I/O Primitives}).
2634 @c sendmsg and recvmsg are like readv and writev in that they
2635 @c use a series of buffers. It's not clear this is worth
2636 @c supporting or that we support them.
2637 @c !!! they can do more; it is hairy
2639 @comment sys/socket.h
2641 @deftp {Data Type} {struct msghdr}
2644 @comment sys/socket.h
2646 @deftypefun int sendmsg (int @var{socket}, const struct msghdr *@var{message}, int @var{flags})
2648 This function is defined as a cancelation point in multi-threaded
2649 programs. So one has to be prepared for this and make sure that
2650 possibly allocated resources (like memory, files descriptors,
2651 semaphores or whatever) are freed even if the thread is cancel.
2652 @c @xref{pthread_cleanup_push}, for a method how to do this.
2655 @comment sys/socket.h
2657 @deftypefun int recvmsg (int @var{socket}, struct msghdr *@var{message}, int @var{flags})
2659 This function is defined as a cancelation point in multi-threaded
2660 programs. So one has to be prepared for this and make sure that
2661 possibly allocated resources (like memory, files descriptors,
2662 semaphores or whatever) are freed even if the thread is canceled.
2663 @c @xref{pthread_cleanup_push}, for a method how to do this.
2667 @node Datagram Example
2668 @subsection Datagram Socket Example
2670 Here is a set of example programs that send messages over a datagram
2671 stream in the local namespace. Both the client and server programs use
2672 the @code{make_named_socket} function that was presented in @ref{Local
2673 Socket Example}, to create and name their sockets.
2675 First, here is the server program. It sits in a loop waiting for
2676 messages to arrive, bouncing each message back to the sender.
2677 Obviously, this isn't a particularly useful program, but it does show
2678 the general ideas involved.
2681 @include filesrv.c.texi
2684 @node Example Receiver
2685 @subsection Example of Reading Datagrams
2687 Here is the client program corresponding to the server above.
2689 It sends a datagram to the server and then waits for a reply. Notice
2690 that the socket for the client (as well as for the server) in this
2691 example has to be given a name. This is so that the server can direct
2692 a message back to the client. Since the socket has no associated
2693 connection state, the only way the server can do this is by
2694 referencing the name of the client.
2697 @include filecli.c.texi
2700 Keep in mind that datagram socket communications are unreliable. In
2701 this example, the client program waits indefinitely if the message
2702 never reaches the server or if the server's response never comes
2703 back. It's up to the user running the program to kill it and restart
2704 it, if desired. A more automatic solution could be to use
2705 @code{select} (@pxref{Waiting for I/O}) to establish a timeout period
2706 for the reply, and in case of timeout either resend the message or
2707 shut down the socket and exit.
2710 @section The @code{inetd} Daemon
2712 We've explained above how to write a server program that does its own
2713 listening. Such a server must already be running in order for anyone
2716 Another way to provide service for an Internet port is to let the daemon
2717 program @code{inetd} do the listening. @code{inetd} is a program that
2718 runs all the time and waits (using @code{select}) for messages on a
2719 specified set of ports. When it receives a message, it accepts the
2720 connection (if the socket style calls for connections) and then forks a
2721 child process to run the corresponding server program. You specify the
2722 ports and their programs in the file @file{/etc/inetd.conf}.
2726 * Configuring Inetd::
2730 @subsection @code{inetd} Servers
2732 Writing a server program to be run by @code{inetd} is very simple. Each time
2733 someone requests a connection to the appropriate port, a new server
2734 process starts. The connection already exists at this time; the
2735 socket is available as the standard input descriptor and as the
2736 standard output descriptor (descriptors 0 and 1) in the server
2737 process. So the server program can begin reading and writing data
2738 right away. Often the program needs only the ordinary I/O facilities;
2739 in fact, a general-purpose filter program that knows nothing about
2740 sockets can work as a byte stream server run by @code{inetd}.
2742 You can also use @code{inetd} for servers that use connectionless
2743 communication styles. For these servers, @code{inetd} does not try to accept
2744 a connection, since no connection is possible. It just starts the
2745 server program, which can read the incoming datagram packet from
2746 descriptor 0. The server program can handle one request and then
2747 exit, or you can choose to write it to keep reading more requests
2748 until no more arrive, and then exit. You must specify which of these
2749 two techniques the server uses, when you configure @code{inetd}.
2751 @node Configuring Inetd
2752 @subsection Configuring @code{inetd}
2754 The file @file{/etc/inetd.conf} tells @code{inetd} which ports to listen to
2755 and what server programs to run for them. Normally each entry in the
2756 file is one line, but you can split it onto multiple lines provided
2757 all but the first line of the entry start with whitespace. Lines that
2758 start with @samp{#} are comments.
2760 Here are two standard entries in @file{/etc/inetd.conf}:
2763 ftp stream tcp nowait root /libexec/ftpd ftpd
2764 talk dgram udp wait root /libexec/talkd talkd
2767 An entry has this format:
2770 @var{service} @var{style} @var{protocol} @var{wait} @var{username} @var{program} @var{arguments}
2773 The @var{service} field says which service this program provides. It
2774 should be the name of a service defined in @file{/etc/services}.
2775 @code{inetd} uses @var{service} to decide which port to listen on for
2778 The fields @var{style} and @var{protocol} specify the communication
2779 style and the protocol to use for the listening socket. The style
2780 should be the name of a communication style, converted to lower case
2781 and with @samp{SOCK_} deleted---for example, @samp{stream} or
2782 @samp{dgram}. @var{protocol} should be one of the protocols listed in
2783 @file{/etc/protocols}. The typical protocol names are @samp{tcp} for
2784 byte stream connections and @samp{udp} for unreliable datagrams.
2786 The @var{wait} field should be either @samp{wait} or @samp{nowait}.
2787 Use @samp{wait} if @var{style} is a connectionless style and the
2788 server, once started, handles multiple requests, as many as come in.
2789 Use @samp{nowait} if @code{inetd} should start a new process for each message
2790 or request that comes in. If @var{style} uses connections, then
2791 @var{wait} @strong{must} be @samp{nowait}.
2793 @var{user} is the user name that the server should run as. @code{inetd} runs
2794 as root, so it can set the user ID of its children arbitrarily. It's
2795 best to avoid using @samp{root} for @var{user} if you can; but some
2796 servers, such as Telnet and FTP, read a username and password
2797 themselves. These servers need to be root initially so they can log
2798 in as commanded by the data coming over the network.
2800 @var{program} together with @var{arguments} specifies the command to
2801 run to start the server. @var{program} should be an absolute file
2802 name specifying the executable file to run. @var{arguments} consists
2803 of any number of whitespace-separated words, which become the
2804 command-line arguments of @var{program}. The first word in
2805 @var{arguments} is argument zero, which should by convention be the
2806 program name itself (sans directories).
2808 If you edit @file{/etc/inetd.conf}, you can tell @code{inetd} to reread the
2809 file and obey its new contents by sending the @code{inetd} process the
2810 @code{SIGHUP} signal. You'll have to use @code{ps} to determine the
2811 process ID of the @code{inetd} process, as it is not fixed.
2813 @c !!! could document /etc/inetd.sec
2815 @node Socket Options
2816 @section Socket Options
2817 @cindex socket options
2819 This section describes how to read or set various options that modify
2820 the behavior of sockets and their underlying communications protocols.
2822 @cindex level, for socket options
2823 @cindex socket option level
2824 When you are manipulating a socket option, you must specify which
2825 @dfn{level} the option pertains to. This describes whether the option
2826 applies to the socket interface, or to a lower-level communications
2830 * Socket Option Functions:: The basic functions for setting and getting
2832 * Socket-Level Options:: Details of the options at the socket level.
2835 @node Socket Option Functions
2836 @subsection Socket Option Functions
2838 @pindex sys/socket.h
2839 Here are the functions for examining and modifying socket options.
2840 They are declared in @file{sys/socket.h}.
2842 @comment sys/socket.h
2844 @deftypefun int getsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t *@var{optlen-ptr})
2845 The @code{getsockopt} function gets information about the value of
2846 option @var{optname} at level @var{level} for socket @var{socket}.
2848 The option value is stored in a buffer that @var{optval} points to.
2849 Before the call, you should supply in @code{*@var{optlen-ptr}} the
2850 size of this buffer; on return, it contains the number of bytes of
2851 information actually stored in the buffer.
2853 Most options interpret the @var{optval} buffer as a single @code{int}
2856 The actual return value of @code{getsockopt} is @code{0} on success
2857 and @code{-1} on failure. The following @code{errno} error conditions
2862 The @var{socket} argument is not a valid file descriptor.
2865 The descriptor @var{socket} is not a socket.
2868 The @var{optname} doesn't make sense for the given @var{level}.
2872 @comment sys/socket.h
2874 @deftypefun int setsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t @var{optlen})
2875 This function is used to set the socket option @var{optname} at level
2876 @var{level} for socket @var{socket}. The value of the option is passed
2877 in the buffer @var{optval}, which has size @var{optlen}.
2882 The return value and error codes for @code{setsockopt} are the same as
2883 for @code{getsockopt}.
2886 The return value and error codes for @code{setsockopt} are the same as
2887 for @code{getsockopt}.
2892 @node Socket-Level Options
2893 @subsection Socket-Level Options
2895 @comment sys/socket.h
2897 @deftypevr Constant int SOL_SOCKET
2898 Use this constant as the @var{level} argument to @code{getsockopt} or
2899 @code{setsockopt} to manipulate the socket-level options described in
2903 @pindex sys/socket.h
2905 Here is a table of socket-level option names; all are defined in the
2906 header file @file{sys/socket.h}.
2909 @comment sys/socket.h
2912 @c Extra blank line here makes the table look better.
2914 This option toggles recording of debugging information in the underlying
2915 protocol modules. The value has type @code{int}; a nonzero value means
2917 @c !!! should say how this is used
2918 @c Ok, anyone who knows, please explain.
2920 @comment sys/socket.h
2923 This option controls whether @code{bind} (@pxref{Setting Address})
2924 should permit reuse of local addresses for this socket. If you enable
2925 this option, you can actually have two sockets with the same Internet
2926 port number; but the system won't allow you to use the two
2927 identically-named sockets in a way that would confuse the Internet. The
2928 reason for this option is that some higher-level Internet protocols,
2929 including FTP, require you to keep reusing the same port number.
2931 The value has type @code{int}; a nonzero value means ``yes''.
2933 @comment sys/socket.h
2936 This option controls whether the underlying protocol should
2937 periodically transmit messages on a connected socket. If the peer
2938 fails to respond to these messages, the connection is considered
2939 broken. The value has type @code{int}; a nonzero value means
2942 @comment sys/socket.h
2945 This option controls whether outgoing messages bypass the normal
2946 message routing facilities. If set, messages are sent directly to the
2947 network interface instead. The value has type @code{int}; a nonzero
2948 value means ``yes''.
2950 @comment sys/socket.h
2953 This option specifies what should happen when the socket of a type
2954 that promises reliable delivery still has untransmitted messages when
2955 it is closed; see @ref{Closing a Socket}. The value has type
2956 @code{struct linger}.
2958 @comment sys/socket.h
2960 @deftp {Data Type} {struct linger}
2961 This structure type has the following members:
2965 This field is interpreted as a boolean. If nonzero, @code{close}
2966 blocks until the data is transmitted or the timeout period has expired.
2969 This specifies the timeout period, in seconds.
2973 @comment sys/socket.h
2976 This option controls whether datagrams may be broadcast from the socket.
2977 The value has type @code{int}; a nonzero value means ``yes''.
2979 @comment sys/socket.h
2982 If this option is set, out-of-band data received on the socket is
2983 placed in the normal input queue. This permits it to be read using
2984 @code{read} or @code{recv} without specifying the @code{MSG_OOB}
2985 flag. @xref{Out-of-Band Data}. The value has type @code{int}; a
2986 nonzero value means ``yes''.
2988 @comment sys/socket.h
2991 This option gets or sets the size of the output buffer. The value is a
2992 @code{size_t}, which is the size in bytes.
2994 @comment sys/socket.h
2997 This option gets or sets the size of the input buffer. The value is a
2998 @code{size_t}, which is the size in bytes.
3000 @comment sys/socket.h
3003 @comment sys/socket.h
3006 This option can be used with @code{getsockopt} only. It is used to
3007 get the socket's communication style. @code{SO_TYPE} is the
3008 historical name, and @code{SO_STYLE} is the preferred name in GNU.
3009 The value has type @code{int} and its value designates a communication
3010 style; see @ref{Communication Styles}.
3012 @comment sys/socket.h
3015 @c Extra blank line here makes the table look better.
3017 This option can be used with @code{getsockopt} only. It is used to reset
3018 the error status of the socket. The value is an @code{int}, which represents
3019 the previous error status.
3020 @c !!! what is "socket error status"? this is never defined.
3023 @node Networks Database
3024 @section Networks Database
3025 @cindex networks database
3026 @cindex converting network number to network name
3027 @cindex converting network name to network number
3029 @pindex /etc/networks
3031 Many systems come with a database that records a list of networks known
3032 to the system developer. This is usually kept either in the file
3033 @file{/etc/networks} or in an equivalent from a name server. This data
3034 base is useful for routing programs such as @code{route}, but it is not
3035 useful for programs that simply communicate over the network. We
3036 provide functions to access this data base, which are declared in
3041 @deftp {Data Type} {struct netent}
3042 This data type is used to represent information about entries in the
3043 networks database. It has the following members:
3047 This is the ``official'' name of the network.
3049 @item char **n_aliases
3050 These are alternative names for the network, represented as a vector
3051 of strings. A null pointer terminates the array.
3053 @item int n_addrtype
3054 This is the type of the network number; this is always equal to
3055 @code{AF_INET} for Internet networks.
3057 @item unsigned long int n_net
3058 This is the network number. Network numbers are returned in host
3059 byte order; see @ref{Byte Order}.
3063 Use the @code{getnetbyname} or @code{getnetbyaddr} functions to search
3064 the networks database for information about a specific network. The
3065 information is returned in a statically-allocated structure; you must
3066 copy the information if you need to save it.
3070 @deftypefun {struct netent *} getnetbyname (const char *@var{name})
3071 The @code{getnetbyname} function returns information about the network
3072 named @var{name}. It returns a null pointer if there is no such
3078 @deftypefun {struct netent *} getnetbyaddr (unsigned long int @var{net}, int @var{type})
3079 The @code{getnetbyaddr} function returns information about the network
3080 of type @var{type} with number @var{net}. You should specify a value of
3081 @code{AF_INET} for the @var{type} argument for Internet networks.
3083 @code{getnetbyaddr} returns a null pointer if there is no such
3087 You can also scan the networks database using @code{setnetent},
3088 @code{getnetent}, and @code{endnetent}. Be careful in using these
3089 functions, because they are not reentrant.
3093 @deftypefun void setnetent (int @var{stayopen})
3094 This function opens and rewinds the networks database.
3096 If the @var{stayopen} argument is nonzero, this sets a flag so that
3097 subsequent calls to @code{getnetbyname} or @code{getnetbyaddr} will
3098 not close the database (as they usually would). This makes for more
3099 efficiency if you call those functions several times, by avoiding
3100 reopening the database for each call.
3105 @deftypefun {struct netent *} getnetent (void)
3106 This function returns the next entry in the networks database. It
3107 returns a null pointer if there are no more entries.
3112 @deftypefun void endnetent (void)
3113 This function closes the networks database.