Update.
[glibc.git] / manual / socket.texi
blobc122106e2b74b38c2a7d02ce3725c82102bfb742
1 @node Sockets, Low-Level Terminal Interface, Pipes and FIFOs, Top
2 @chapter Sockets
4 This chapter describes the GNU facilities for interprocess
5 communication using sockets.
7 @cindex socket
8 @cindex interprocess communication, with sockets
9 A @dfn{socket} is a generalized interprocess communication channel.
10 Like a pipe, a socket is represented as a file descriptor.  But,
11 unlike pipes, sockets support communication between unrelated
12 processes, and even between processes running on different machines
13 that communicate over a network.  Sockets are the primary means of
14 communicating with other machines; @code{telnet}, @code{rlogin},
15 @code{ftp}, @code{talk}, and the other familiar network programs use
16 sockets.
18 Not all operating systems support sockets.  In the GNU library, the
19 header file @file{sys/socket.h} exists regardless of the operating
20 system, and the socket functions always exist, but if the system does
21 not really support sockets, these functions always fail.
23 @strong{Incomplete:} We do not currently document the facilities for
24 broadcast messages or for configuring Internet interfaces.
26 @menu
27 * Socket Concepts::     Basic concepts you need to know about.
28 * Communication Styles::Stream communication, datagrams, and other styles.
29 * Socket Addresses::    How socket names (``addresses'') work.
30 * File Namespace::      Details about the file namespace.
31 * Internet Namespace::  Details about the Internet namespace.
32 * Misc Namespaces::     Other namespaces not documented fully here.
33 * Open/Close Sockets::  Creating sockets and destroying them.
34 * Connections::         Operations on sockets with connection state.
35 * Datagrams::           Operations on datagram sockets.
36 * Inetd::               Inetd is a daemon that starts servers on request.
37                            The most convenient way to write a server
38                            is to make it work with Inetd.
39 * Socket Options::      Miscellaneous low-level socket options.
40 * Networks Database::   Accessing the database of network names.
41 @end menu
43 @node Socket Concepts
44 @section Socket Concepts
46 @cindex communication style (of a socket)
47 @cindex style of communication (of a socket)
48 When you create a socket, you must specify the style of communication
49 you want to use and the type of protocol that should implement it.
50 The @dfn{communication style} of a socket defines the user-level
51 semantics of sending and receiving data on the socket.  Choosing a
52 communication style specifies the answers to questions such as these:
54 @itemize @bullet
55 @item
56 @cindex packet
57 @cindex byte stream
58 @cindex stream (sockets)
59 @strong{What are the units of data transmission?}  Some communication
60 styles regard the data as a sequence of bytes, with no larger
61 structure; others group the bytes into records (which are known in
62 this context as @dfn{packets}).
64 @item
65 @cindex loss of data on sockets
66 @cindex data loss on sockets
67 @strong{Can data be lost during normal operation?}  Some communication
68 styles guarantee that all the data sent arrives in the order it was
69 sent (barring system or network crashes); other styles occasionally
70 lose data as a normal part of operation, and may sometimes deliver
71 packets more than once or in the wrong order.
73 Designing a program to use unreliable communication styles usually
74 involves taking precautions to detect lost or misordered packets and
75 to retransmit data as needed.
77 @item
78 @strong{Is communication entirely with one partner?}  Some
79 communication styles are like a telephone call---you make a
80 @dfn{connection} with one remote socket, and then exchange data
81 freely.  Other styles are like mailing letters---you specify a
82 destination address for each message you send.
83 @end itemize
85 @cindex namespace (of socket)
86 @cindex domain (of socket)
87 @cindex socket namespace
88 @cindex socket domain
89 You must also choose a @dfn{namespace} for naming the socket.  A socket
90 name (``address'') is meaningful only in the context of a particular
91 namespace.  In fact, even the data type to use for a socket name may
92 depend on the namespace.  Namespaces are also called ``domains'', but we
93 avoid that word as it can be confused with other usage of the same
94 term.  Each namespace has a symbolic name that starts with @samp{PF_}.
95 A corresponding symbolic name starting with @samp{AF_} designates the
96 address format for that namespace.
98 @cindex network protocol
99 @cindex protocol (of socket)
100 @cindex socket protocol
101 @cindex protocol family
102 Finally you must choose the @dfn{protocol} to carry out the
103 communication.  The protocol determines what low-level mechanism is used
104 to transmit and receive data.  Each protocol is valid for a particular
105 namespace and communication style; a namespace is sometimes called a
106 @dfn{protocol family} because of this, which is why the namespace names
107 start with @samp{PF_}.
109 The rules of a protocol apply to the data passing between two programs,
110 perhaps on different computers; most of these rules are handled by the
111 operating system, and you need not know about them.  What you do need to
112 know about protocols is this:
114 @itemize @bullet
115 @item
116 In order to have communication between two sockets, they must specify
117 the @emph{same} protocol.
119 @item
120 Each protocol is meaningful with particular style/namespace
121 combinations and cannot be used with inappropriate combinations.  For
122 example, the TCP protocol fits only the byte stream style of
123 communication and the Internet namespace.
125 @item
126 For each combination of style and namespace, there is a @dfn{default
127 protocol} which you can request by specifying 0 as the protocol
128 number.  And that's what you should normally do---use the default.
129 @end itemize
131 @node Communication Styles
132 @section Communication Styles
134 The GNU library includes support for several different kinds of sockets,
135 each with different characteristics.  This section describes the
136 supported socket types.  The symbolic constants listed here are
137 defined in @file{sys/socket.h}.
138 @pindex sys/socket.h
140 @comment sys/socket.h
141 @comment BSD
142 @deftypevr Macro int SOCK_STREAM
143 The @code{SOCK_STREAM} style is like a pipe (@pxref{Pipes and FIFOs});
144 it operates over a connection with a particular remote socket, and
145 transmits data reliably as a stream of bytes.
147 Use of this style is covered in detail in @ref{Connections}.
148 @end deftypevr
150 @comment sys/socket.h
151 @comment BSD
152 @deftypevr Macro int SOCK_DGRAM
153 The @code{SOCK_DGRAM} style is used for sending
154 individually-addressed packets, unreliably.
155 It is the diametrical opposite of @code{SOCK_STREAM}.
157 Each time you write data to a socket of this kind, that data becomes
158 one packet.  Since @code{SOCK_DGRAM} sockets do not have connections,
159 you must specify the recipient address with each packet.
161 The only guarantee that the system makes about your requests to
162 transmit data is that it will try its best to deliver each packet you
163 send.  It may succeed with the sixth packet after failing with the
164 fourth and fifth packets; the seventh packet may arrive before the
165 sixth, and may arrive a second time after the sixth.
167 The typical use for @code{SOCK_DGRAM} is in situations where it is
168 acceptable to simply resend a packet if no response is seen in a
169 reasonable amount of time.
171 @xref{Datagrams}, for detailed information about how to use datagram
172 sockets.
173 @end deftypevr
175 @ignore
176 @c This appears to be only for the NS domain, which we aren't
177 @c discussing and probably won't support either.
178 @comment sys/socket.h
179 @comment BSD
180 @deftypevr Macro int SOCK_SEQPACKET
181 This style is like @code{SOCK_STREAM} except that the data is
182 structured into packets.
184 A program that receives data over a @code{SOCK_SEQPACKET} socket
185 should be prepared to read the entire message packet in a single call
186 to @code{read}; if it only reads part of the message, the remainder of
187 the message is simply discarded instead of being available for
188 subsequent calls to @code{read}.
190 Many protocols do not support this communication style.
191 @end deftypevr
192 @end ignore
194 @ignore
195 @comment sys/socket.h
196 @comment BSD
197 @deftypevr Macro int SOCK_RDM
198 This style is a reliable version of @code{SOCK_DGRAM}: it sends
199 individually addressed packets, but guarantees that each packet sent
200 arrives exactly once.
202 @strong{Warning:} It is not clear this is actually supported
203 by any operating system.
204 @end deftypevr
205 @end ignore
207 @comment sys/socket.h
208 @comment BSD
209 @deftypevr Macro int SOCK_RAW
210 This style provides access to low-level network protocols and
211 interfaces.  Ordinary user programs usually have no need to use this
212 style.
213 @end deftypevr
215 @node Socket Addresses
216 @section Socket Addresses
218 @cindex address of socket
219 @cindex name of socket
220 @cindex binding a socket address
221 @cindex socket address (name) binding
222 The name of a socket is normally called an @dfn{address}.  The
223 functions and symbols for dealing with socket addresses were named
224 inconsistently, sometimes using the term ``name'' and sometimes using
225 ``address''.  You can regard these terms as synonymous where sockets
226 are concerned.
228 A socket newly created with the @code{socket} function has no
229 address.  Other processes can find it for communication only if you
230 give it an address.  We call this @dfn{binding} the address to the
231 socket, and the way to do it is with the @code{bind} function.
233 You need be concerned with the address of a socket if other processes
234 are to find it and start communicating with it.  You can specify an
235 address for other sockets, but this is usually pointless; the first time
236 you send data from a socket, or use it to initiate a connection, the
237 system assigns an address automatically if you have not specified one.
239 Occasionally a client needs to specify an address because the server
240 discriminates based on addresses; for example, the rsh and rlogin
241 protocols look at the client's socket address and don't bypass password
242 checking unless it is less than @code{IPPORT_RESERVED} (@pxref{Ports}).
244 The details of socket addresses vary depending on what namespace you are
245 using.  @xref{File Namespace}, or @ref{Internet Namespace}, for specific
246 information.
248 Regardless of the namespace, you use the same functions @code{bind} and
249 @code{getsockname} to set and examine a socket's address.  These
250 functions use a phony data type, @code{struct sockaddr *}, to accept the
251 address.  In practice, the address lives in a structure of some other
252 data type appropriate to the address format you are using, but you cast
253 its address to @code{struct sockaddr *} when you pass it to
254 @code{bind}.
256 @menu
257 * Address Formats::             About @code{struct sockaddr}.
258 * Setting Address::             Binding an address to a socket.
259 * Reading Address::             Reading the address of a socket.
260 @end menu
262 @node Address Formats
263 @subsection Address Formats
265 The functions @code{bind} and @code{getsockname} use the generic data
266 type @code{struct sockaddr *} to represent a pointer to a socket
267 address.  You can't use this data type effectively to interpret an
268 address or construct one; for that, you must use the proper data type
269 for the socket's namespace.
271 Thus, the usual practice is to construct an address in the proper
272 namespace-specific type, then cast a pointer to @code{struct sockaddr *}
273 when you call @code{bind} or @code{getsockname}.
275 The one piece of information that you can get from the @code{struct
276 sockaddr} data type is the @dfn{address format} designator which tells
277 you which data type to use to understand the address fully.
279 @pindex sys/socket.h
280 The symbols in this section are defined in the header file
281 @file{sys/socket.h}.
283 @comment sys/socket.h
284 @comment BSD
285 @deftp {Date Type} {struct sockaddr}
286 The @code{struct sockaddr} type itself has the following members:
288 @table @code
289 @item short int sa_family
290 This is the code for the address format of this address.  It
291 identifies the format of the data which follows.
293 @item char sa_data[14]
294 This is the actual socket address data, which is format-dependent.  Its
295 length also depends on the format, and may well be more than 14.  The
296 length 14 of @code{sa_data} is essentially arbitrary.
297 @end table
298 @end deftp
300 Each address format has a symbolic name which starts with @samp{AF_}.
301 Each of them corresponds to a @samp{PF_} symbol which designates the
302 corresponding namespace.  Here is a list of address format names:
304 @table @code
305 @comment sys/socket.h
306 @comment GNU
307 @item AF_FILE
308 @vindex AF_FILE
309 This designates the address format that goes with the file namespace.
310 (@code{PF_FILE} is the name of that namespace.)  @xref{File Namespace
311 Details}, for information about this address format.
313 @comment sys/socket.h
314 @comment BSD
315 @item AF_UNIX
316 @vindex AF_UNIX
317 This is a synonym for @code{AF_FILE}, for compatibility.
318 (@code{PF_UNIX} is likewise a synonym for @code{PF_FILE}.)
320 @comment sys/socket.h
321 @comment BSD
322 @item AF_INET
323 @vindex AF_INET
324 This designates the address format that goes with the Internet
325 namespace.  (@code{PF_INET} is the name of that namespace.)
326 @xref{Internet Address Format}.
328 @comment sys/socket.h
329 @comment BSD
330 @item AF_UNSPEC
331 @vindex AF_UNSPEC
332 This designates no particular address format.  It is used only in rare
333 cases, such as to clear out the default destination address of a
334 ``connected'' datagram socket.  @xref{Sending Datagrams}.
336 The corresponding namespace designator symbol @code{PF_UNSPEC} exists
337 for completeness, but there is no reason to use it in a program.
338 @end table
340 @file{sys/socket.h} defines symbols starting with @samp{AF_} for many
341 different kinds of networks, all or most of which are not actually
342 implemented.  We will document those that really work, as we receive
343 information about how to use them.
345 @node Setting Address
346 @subsection Setting the Address of a Socket
348 @pindex sys/socket.h
349 Use the @code{bind} function to assign an address to a socket.  The
350 prototype for @code{bind} is in the header file @file{sys/socket.h}.
351 For examples of use, see @ref{File Namespace}, or see @ref{Inet Example}.
353 @comment sys/socket.h
354 @comment BSD
355 @deftypefun int bind (int @var{socket}, struct sockaddr *@var{addr}, size_t @var{length})
356 The @code{bind} function assigns an address to the socket
357 @var{socket}.  The @var{addr} and @var{length} arguments specify the
358 address; the detailed format of the address depends on the namespace.
359 The first part of the address is always the format designator, which
360 specifies a namespace, and says that the address is in the format for
361 that namespace.
363 The return value is @code{0} on success and @code{-1} on failure.  The
364 following @code{errno} error conditions are defined for this function:
366 @table @code
367 @item EBADF
368 The @var{socket} argument is not a valid file descriptor.
370 @item ENOTSOCK
371 The descriptor @var{socket} is not a socket.
373 @item EADDRNOTAVAIL
374 The specified address is not available on this machine.
376 @item EADDRINUSE
377 Some other socket is already using the specified address.
379 @item EINVAL
380 The socket @var{socket} already has an address.
382 @item EACCES
383 You do not have permission to access the requested address.  (In the
384 Internet domain, only the super-user is allowed to specify a port number
385 in the range 0 through @code{IPPORT_RESERVED} minus one; see
386 @ref{Ports}.)
387 @end table
389 Additional conditions may be possible depending on the particular namespace
390 of the socket.
391 @end deftypefun
393 @node Reading Address
394 @subsection Reading the Address of a Socket
396 @pindex sys/socket.h
397 Use the function @code{getsockname} to examine the address of an
398 Internet socket.  The prototype for this function is in the header file
399 @file{sys/socket.h}.
401 @comment sys/socket.h
402 @comment BSD
403 @deftypefun int getsockname (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
404 The @code{getsockname} function returns information about the
405 address of the socket @var{socket} in the locations specified by the
406 @var{addr} and @var{length-ptr} arguments.  Note that the
407 @var{length-ptr} is a pointer; you should initialize it to be the
408 allocation size of @var{addr}, and on return it contains the actual
409 size of the address data.
411 The format of the address data depends on the socket namespace.  The
412 length of the information is usually fixed for a given namespace, so
413 normally you can know exactly how much space is needed and can provide
414 that much.  The usual practice is to allocate a place for the value
415 using the proper data type for the socket's namespace, then cast its
416 address to @code{struct sockaddr *} to pass it to @code{getsockname}.
418 The return value is @code{0} on success and @code{-1} on error.  The
419 following @code{errno} error conditions are defined for this function:
421 @table @code
422 @item EBADF
423 The @var{socket} argument is not a valid file descriptor.
425 @item ENOTSOCK
426 The descriptor @var{socket} is not a socket.
428 @item ENOBUFS
429 There are not enough internal buffers available for the operation.
430 @end table
431 @end deftypefun
433 You can't read the address of a socket in the file namespace.  This is
434 consistent with the rest of the system; in general, there's no way to
435 find a file's name from a descriptor for that file.
437 @node File Namespace
438 @section The File Namespace
439 @cindex file namespace, for sockets
441 This section describes the details of the file namespace, whose
442 symbolic name (required when you create a socket) is @code{PF_FILE}.
444 @menu
445 * Concepts: File Namespace Concepts.    What you need to understand.
446 * Details: File Namespace Details.      Address format, symbolic names, etc.
447 * Example: File Socket Example.         Example of creating a socket.
448 @end menu
450 @node File Namespace Concepts
451 @subsection File Namespace Concepts
453 In the file namespace, socket addresses are file names.  You can specify
454 any file name you want as the address of the socket, but you must have
455 write permission on the directory containing it.  In order to connect to
456 a socket, you must have read permission for it.  It's common to put
457 these files in the @file{/tmp} directory.
459 One peculiarity of the file namespace is that the name is only used when
460 opening the connection; once that is over with, the address is not
461 meaningful and may not exist.
463 Another peculiarity is that you cannot connect to such a socket from
464 another machine--not even if the other machine shares the file system
465 which contains the name of the socket.  You can see the socket in a
466 directory listing, but connecting to it never succeeds.  Some programs
467 take advantage of this, such as by asking the client to send its own
468 process ID, and using the process IDs to distinguish between clients.
469 However, we recommend you not use this method in protocols you design,
470 as we might someday permit connections from other machines that mount
471 the same file systems.  Instead, send each new client an identifying
472 number if you want it to have one.
474 After you close a socket in the file namespace, you should delete the
475 file name from the file system.  Use @code{unlink} or @code{remove} to
476 do this; see @ref{Deleting Files}.
478 The file namespace supports just one protocol for any communication
479 style; it is protocol number @code{0}.
481 @node File Namespace Details
482 @subsection Details of File Namespace
484 @pindex sys/socket.h
485 To create a socket in the file namespace, use the constant
486 @code{PF_FILE} as the @var{namespace} argument to @code{socket} or
487 @code{socketpair}.  This constant is defined in @file{sys/socket.h}.
489 @comment sys/socket.h
490 @comment GNU
491 @deftypevr Macro int PF_FILE
492 This designates the file namespace, in which socket addresses are file
493 names, and its associated family of protocols.
494 @end deftypevr
496 @comment sys/socket.h
497 @comment BSD
498 @deftypevr Macro int PF_UNIX
499 This is a synonym for @code{PF_FILE}, for compatibility's sake.
500 @end deftypevr
502 The structure for specifying socket names in the file namespace is
503 defined in the header file @file{sys/un.h}:
504 @pindex sys/un.h
506 @comment sys/un.h
507 @comment BSD
508 @deftp {Data Type} {struct sockaddr_un}
509 This structure is used to specify file namespace socket addresses.  It has
510 the following members:
512 @table @code
513 @item short int sun_family
514 This identifies the address family or format of the socket address.
515 You should store the value @code{AF_FILE} to designate the file
516 namespace.  @xref{Socket Addresses}.
518 @item char sun_path[108]
519 This is the file name to use.
521 @strong{Incomplete:}  Why is 108 a magic number?  RMS suggests making
522 this a zero-length array and tweaking the example following to use
523 @code{alloca} to allocate an appropriate amount of storage based on
524 the length of the filename.
525 @end table
526 @end deftp
528 You should compute the @var{length} parameter for a socket address in
529 the file namespace as the sum of the size of the @code{sun_family}
530 component and the string length (@emph{not} the allocation size!) of
531 the file name string.
533 @node File Socket Example
534 @subsection Example of File-Namespace Sockets
536 Here is an example showing how to create and name a socket in the file
537 namespace.
539 @smallexample
540 @include mkfsock.c.texi
541 @end smallexample
543 @node Internet Namespace
544 @section The Internet Namespace
545 @cindex Internet namespace, for sockets
547 This section describes the details the protocols and socket naming
548 conventions used in the Internet namespace.
550 To create a socket in the Internet namespace, use the symbolic name
551 @code{PF_INET} of this namespace as the @var{namespace} argument to
552 @code{socket} or @code{socketpair}.  This macro is defined in
553 @file{sys/socket.h}.
554 @pindex sys/socket.h
556 @comment sys/socket.h
557 @comment BSD
558 @deftypevr Macro int PF_INET
559 This designates the Internet namespace and associated family of
560 protocols.
561 @end deftypevr
563 A socket address for the Internet namespace includes the following components:
565 @itemize @bullet
566 @item
567 The address of the machine you want to connect to.  Internet addresses
568 can be specified in several ways; these are discussed in @ref{Internet
569 Address Format}, @ref{Host Addresses}, and @ref{Host Names}.
571 @item
572 A port number for that machine.  @xref{Ports}.
573 @end itemize
575 You must ensure that the address and port number are represented in a
576 canonical format called @dfn{network byte order}.  @xref{Byte Order},
577 for information about this.
579 @menu
580 * Internet Address Format::     How socket addresses are specified in the
581                                  Internet namespace.
582 * Host Addresses::              All about host addresses of internet host.
583 * Protocols Database::          Referring to protocols by name.
584 * Ports::                       Internet port numbers.
585 * Services Database::           Ports may have symbolic names.
586 * Byte Order::                  Different hosts may use different byte
587                                  ordering conventions; you need to
588                                  canonicalize host address and port number.
589 * Inet Example::                Putting it all together.
590 @end menu
592 @node Internet Address Format
593 @subsection Internet Socket Address Format
595 In the Internet namespace, a socket address consists of a host address
596 and a port on that host.  In addition, the protocol you choose serves
597 effectively as a part of the address because local port numbers are
598 meaningful only within a particular protocol.
600 The data type for representing socket addresses in the Internet namespace
601 is defined in the header file @file{netinet/in.h}.
602 @pindex netinet/in.h
604 @comment netinet/in.h
605 @comment BSD
606 @deftp {Data Type} {struct sockaddr_in}
607 This is the data type used to represent socket addresses in the
608 Internet namespace.  It has the following members:
610 @table @code
611 @item short int sin_family
612 This identifies the address family or format of the socket address.
613 You should store the value of @code{AF_INET} in this member.
614 @xref{Socket Addresses}.
616 @item struct in_addr sin_addr
617 This is the Internet address of the host machine.  @xref{Host
618 Addresses}, and @ref{Host Names}, for how to get a value to store
619 here.
621 @item unsigned short int sin_port
622 This is the port number.  @xref{Ports}.
623 @end table
624 @end deftp
626 When you call @code{bind} or @code{getsockname}, you should specify
627 @code{sizeof (struct sockaddr_in)} as the @var{length} parameter if
628 you are using an Internet namespace socket address.
630 @node Host Addresses
631 @subsection Host Addresses
633 Each computer on the Internet has one or more @dfn{Internet addresses},
634 numbers which identify that computer among all those on the Internet.
635 Users typically write numeric host addresses as sequences of four
636 numbers, separated by periods, as in @samp{128.52.46.32}.
638 Each computer also has one or more @dfn{host names}, which are strings
639 of words separated by periods, as in @samp{churchy.gnu.ai.mit.edu}.
641 Programs that let the user specify a host typically accept both numeric
642 addresses and host names.  But the program needs a numeric address to
643 open a connection; to use a host name, you must convert it to the
644 numeric address it stands for.
646 @menu
647 * Abstract Host Addresses::     What a host number consists of.
648 * Data type: Host Address Data Type.    Data type for a host number.
649 * Functions: Host Address Functions.    Functions to operate on them.
650 * Names: Host Names.            Translating host names to host numbers.
651 @end menu
653 @node Abstract Host Addresses
654 @subsubsection Internet Host Addresses
655 @cindex host address, Internet
656 @cindex Internet host address
658 @ifinfo
659 Each computer on the Internet has one or more Internet addresses,
660 numbers which identify that computer among all those on the Internet.
661 @end ifinfo
663 @cindex network number
664 @cindex local network address number
665 An Internet host address is a number containing four bytes of data.
666 These are divided into two parts, a @dfn{network number} and a
667 @dfn{local network address number} within that network.  The network
668 number consists of the first one, two or three bytes; the rest of the
669 bytes are the local address.
671 Network numbers are registered with the Network Information Center
672 (NIC), and are divided into three classes---A, B, and C.  The local
673 network address numbers of individual machines are registered with the
674 administrator of the particular network.
676 Class A networks have single-byte numbers in the range 0 to 127.  There
677 are only a small number of Class A networks, but they can each support a
678 very large number of hosts.  Medium-sized Class B networks have two-byte
679 network numbers, with the first byte in the range 128 to 191.  Class C
680 networks are the smallest; they have three-byte network numbers, with
681 the first byte in the range 192-255.  Thus, the first 1, 2, or 3 bytes
682 of an Internet address specifies a network.  The remaining bytes of the
683 Internet address specify the address within that network.
685 The Class A network 0 is reserved for broadcast to all networks.  In
686 addition, the host number 0 within each network is reserved for broadcast
687 to all hosts in that network.
689 The Class A network 127 is reserved for loopback; you can always use
690 the Internet address @samp{127.0.0.1} to refer to the host machine.
692 Since a single machine can be a member of multiple networks, it can
693 have multiple Internet host addresses.  However, there is never
694 supposed to be more than one machine with the same host address.
696 @c !!! this section could document the IN_CLASS* macros in <netinet/in.h>.
698 @cindex standard dot notation, for Internet addresses
699 @cindex dot notation, for Internet addresses
700 There are four forms of the @dfn{standard numbers-and-dots notation}
701 for Internet addresses:
703 @table @code
704 @item @var{a}.@var{b}.@var{c}.@var{d}
705 This specifies all four bytes of the address individually.
707 @item @var{a}.@var{b}.@var{c}
708 The last part of the address, @var{c}, is interpreted as a 2-byte quantity.
709 This is useful for specifying host addresses in a Class B network with
710 network address number @code{@var{a}.@var{b}}.
712 @item @var{a}.@var{b}
713 The last part of the address, @var{c}, is interpreted as a 3-byte quantity.
714 This is useful for specifying host addresses in a Class A network with
715 network address number @var{a}.
717 @item @var{a}
718 If only one part is given, this corresponds directly to the host address
719 number.
720 @end table
722 Within each part of the address, the usual C conventions for specifying
723 the radix apply.  In other words, a leading @samp{0x} or @samp{0X} implies
724 hexadecimal radix; a leading @samp{0} implies octal; and otherwise decimal
725 radix is assumed.
727 @node Host Address Data Type
728 @subsubsection Host Address Data Type
730 Internet host addresses are represented in some contexts as integers
731 (type @code{unsigned long int}).  In other contexts, the integer is
732 packaged inside a structure of type @code{struct in_addr}.  It would
733 be better if the usage were made consistent, but it is not hard to extract
734 the integer from the structure or put the integer into a structure.
736 The following basic definitions for Internet addresses appear in the
737 header file @file{netinet/in.h}:
738 @pindex netinet/in.h
740 @comment netinet/in.h
741 @comment BSD
742 @deftp {Data Type} {struct in_addr}
743 This data type is used in certain contexts to contain an Internet host
744 address.  It has just one field, named @code{s_addr}, which records the
745 host address number as an @code{unsigned long int}.
746 @end deftp
748 @comment netinet/in.h
749 @comment BSD
750 @deftypevr Macro {unsigned int} INADDR_LOOPBACK
751 You can use this constant to stand for ``the address of this machine,''
752 instead of finding its actual address.  It is the Internet address
753 @samp{127.0.0.1}, which is usually called @samp{localhost}.  This
754 special constant saves you the trouble of looking up the address of your
755 own machine.  Also, the system usually implements @code{INADDR_LOOPBACK}
756 specially, avoiding any network traffic for the case of one machine
757 talking to itself.
758 @end deftypevr
760 @comment netinet/in.h
761 @comment BSD
762 @deftypevr Macro {unsigned int} INADDR_ANY
763 You can use this constant to stand for ``any incoming address,'' when
764 binding to an address.  @xref{Setting Address}.  This is the usual
765 address to give in the @code{sin_addr} member of @w{@code{struct
766 sockaddr_in}} when you want to accept Internet connections.
767 @end deftypevr
769 @comment netinet/in.h
770 @comment BSD
771 @deftypevr Macro {unsigned int} INADDR_BROADCAST
772 This constant is the address you use to send a broadcast message.
773 @c !!! broadcast needs further documented
774 @end deftypevr
776 @comment netinet/in.h
777 @comment BSD
778 @deftypevr Macro {unsigned int} INADDR_NONE
779 This constant is returned by some functions to indicate an error.
780 @end deftypevr
782 @node Host Address Functions
783 @subsubsection Host Address Functions
785 @pindex arpa/inet.h
786 These additional functions for manipulating Internet addresses are
787 declared in @file{arpa/inet.h}.  They represent Internet addresses in
788 network byte order; they represent network numbers and
789 local-address-within-network numbers in host byte order.
790 @xref{Byte Order}, for an explanation of network and host byte order.
792 @comment arpa/inet.h
793 @comment BSD
794 @deftypefun {int} inet_aton (const char *@var{name}, struct in_addr *@var{addr})
795 This function converts the Internet host address @var{name}
796 from the standard numbers-and-dots notation into binary data and stores
797 it in the @code{struct in_addr} that @var{addr} points to.
798 @code{inet_aton} returns nonzero if the address is valid, zero if not.
799 @end deftypefun
801 @comment arpa/inet.h
802 @comment BSD
803 @deftypefun {unsigned long int} inet_addr (const char *@var{name})
804 This function converts the Internet host address @var{name} from the
805 standard numbers-and-dots notation into binary data.  If the input is
806 not valid, @code{inet_addr} returns @code{INADDR_NONE}.  This is an
807 obsolete interface to @code{inet_aton}, described immediately above; it
808 is obsolete because @code{INADDR_NONE} is a valid address
809 (255.255.255.255), and @code{inet_aton} provides a cleaner way to
810 indicate error return.
811 @end deftypefun
813 @comment arpa/inet.h
814 @comment BSD
815 @deftypefun {unsigned long int} inet_network (const char *@var{name})
816 This function extracts the network number from the address @var{name},
817 given in the standard numbers-and-dots notation.
818 If the input is not valid, @code{inet_network} returns @code{-1}.
819 @end deftypefun
821 @comment arpa/inet.h
822 @comment BSD
823 @deftypefun {char *} inet_ntoa (struct in_addr @var{addr})
824 This function converts the Internet host address @var{addr} to a
825 string in the standard numbers-and-dots notation.  The return value is
826 a pointer into a statically-allocated buffer.  Subsequent calls will
827 overwrite the same buffer, so you should copy the string if you need
828 to save it.
830 In multi-threaded programs each thread has an own statically-allocated
831 buffer.  But still subsequent calls of @code{inet_ntoa} in the same
832 thread will overwrite the result of the last call.
833 @end deftypefun
835 @comment arpa/inet.h
836 @comment BSD
837 @deftypefun {struct in_addr} inet_makeaddr (int @var{net}, int @var{local})
838 This function makes an Internet host address by combining the network
839 number @var{net} with the local-address-within-network number
840 @var{local}.
841 @end deftypefun
843 @comment arpa/inet.h
844 @comment BSD
845 @deftypefun int inet_lnaof (struct in_addr @var{addr})
846 This function returns the local-address-within-network part of the
847 Internet host address @var{addr}.
848 @end deftypefun
850 @comment arpa/inet.h
851 @comment BSD
852 @deftypefun int inet_netof (struct in_addr @var{addr})
853 This function returns the network number part of the Internet host
854 address @var{addr}.
855 @end deftypefun
857 @node Host Names
858 @subsubsection Host Names
859 @cindex hosts database
860 @cindex converting host name to address
861 @cindex converting host address to name
863 Besides the standard numbers-and-dots notation for Internet addresses,
864 you can also refer to a host by a symbolic name.  The advantage of a
865 symbolic name is that it is usually easier to remember.  For example,
866 the machine with Internet address @samp{128.52.46.32} is also known as
867 @samp{churchy.gnu.ai.mit.edu}; and other machines in the @samp{gnu.ai.mit.edu}
868 domain can refer to it simply as @samp{churchy}.
870 @pindex /etc/hosts
871 @pindex netdb.h
872 Internally, the system uses a database to keep track of the mapping
873 between host names and host numbers.  This database is usually either
874 the file @file{/etc/hosts} or an equivalent provided by a name server.
875 The functions and other symbols for accessing this database are declared
876 in @file{netdb.h}.  They are BSD features, defined unconditionally if
877 you include @file{netdb.h}.
879 @comment netdb.h
880 @comment BSD
881 @deftp {Data Type} {struct hostent}
882 This data type is used to represent an entry in the hosts database.  It
883 has the following members:
885 @table @code
886 @item char *h_name
887 This is the ``official'' name of the host.
889 @item char **h_aliases
890 These are alternative names for the host, represented as a null-terminated
891 vector of strings.
893 @item int h_addrtype
894 This is the host address type; in practice, its value is always
895 @code{AF_INET}.  In principle other kinds of addresses could be
896 represented in the data base as well as Internet addresses; if this were
897 done, you might find a value in this field other than @code{AF_INET}.
898 @xref{Socket Addresses}.
900 @item int h_length
901 This is the length, in bytes, of each address.
903 @item char **h_addr_list
904 This is the vector of addresses for the host.  (Recall that the host
905 might be connected to multiple networks and have different addresses on
906 each one.)  The vector is terminated by a null pointer.
908 @item char *h_addr
909 This is a synonym for @code{h_addr_list[0]}; in other words, it is the
910 first host address.
911 @end table
912 @end deftp
914 As far as the host database is concerned, each address is just a block
915 of memory @code{h_length} bytes long.  But in other contexts there is an
916 implicit assumption that you can convert this to a @code{struct in_addr} or
917 an @code{unsigned long int}.  Host addresses in a @code{struct hostent}
918 structure are always given in network byte order; see @ref{Byte Order}.
920 You can use @code{gethostbyname} or @code{gethostbyaddr} to search the
921 hosts database for information about a particular host.  The information
922 is returned in a statically-allocated structure; you must copy the
923 information if you need to save it across calls.
925 @comment netdb.h
926 @comment BSD
927 @deftypefun {struct hostent *} gethostbyname (const char *@var{name})
928 The @code{gethostbyname} function returns information about the host
929 named @var{name}.  If the lookup fails, it returns a null pointer.
930 @end deftypefun
932 @comment netdb.h
933 @comment BSD
934 @deftypefun {struct hostent *} gethostbyaddr (const char *@var{addr}, int @var{length}, int @var{format})
935 The @code{gethostbyaddr} function returns information about the host
936 with Internet address @var{addr}.  The @var{length} argument is the
937 size (in bytes) of the address at @var{addr}.  @var{format} specifies
938 the address format; for an Internet address, specify a value of
939 @code{AF_INET}.
941 If the lookup fails, @code{gethostbyaddr} returns a null pointer.
942 @end deftypefun
944 @vindex h_errno
945 If the name lookup by @code{gethostbyname} or @code{gethostbyaddr}
946 fails, you can find out the reason by looking at the value of the
947 variable @code{h_errno}.  (It would be cleaner design for these
948 functions to set @code{errno}, but use of @code{h_errno} is compatible
949 with other systems.)  Before using @code{h_errno}, you must declare it
950 like this:
952 @smallexample
953 extern int h_errno;
954 @end smallexample
956 Here are the error codes that you may find in @code{h_errno}:
958 @table @code
959 @comment netdb.h
960 @comment BSD
961 @item HOST_NOT_FOUND
962 @vindex HOST_NOT_FOUND
963 No such host is known in the data base.
965 @comment netdb.h
966 @comment BSD
967 @item TRY_AGAIN
968 @vindex TRY_AGAIN
969 This condition happens when the name server could not be contacted.  If
970 you try again later, you may succeed then.
972 @comment netdb.h
973 @comment BSD
974 @item NO_RECOVERY
975 @vindex NO_RECOVERY
976 A non-recoverable error occurred.
978 @comment netdb.h
979 @comment BSD
980 @item NO_ADDRESS
981 @vindex NO_ADDRESS
982 The host database contains an entry for the name, but it doesn't have an
983 associated Internet address.
984 @end table
986 You can also scan the entire hosts database one entry at a time using
987 @code{sethostent}, @code{gethostent}, and @code{endhostent}.  Be careful
988 in using these functions, because they are not reentrant.
990 @comment netdb.h
991 @comment BSD
992 @deftypefun void sethostent (int @var{stayopen})
993 This function opens the hosts database to begin scanning it.  You can
994 then call @code{gethostent} to read the entries.
996 @c There was a rumor that this flag has different meaning if using the DNS,
997 @c but it appears this description is accurate in that case also.
998 If the @var{stayopen} argument is nonzero, this sets a flag so that
999 subsequent calls to @code{gethostbyname} or @code{gethostbyaddr} will
1000 not close the database (as they usually would).  This makes for more
1001 efficiency if you call those functions several times, by avoiding
1002 reopening the database for each call.
1003 @end deftypefun
1005 @comment netdb.h
1006 @comment BSD
1007 @deftypefun {struct hostent *} gethostent ()
1008 This function returns the next entry in the hosts database.  It
1009 returns a null pointer if there are no more entries.
1010 @end deftypefun
1012 @comment netdb.h
1013 @comment BSD
1014 @deftypefun void endhostent ()
1015 This function closes the hosts database.
1016 @end deftypefun
1018 @node Ports
1019 @subsection Internet Ports
1020 @cindex port number
1022 A socket address in the Internet namespace consists of a machine's
1023 Internet address plus a @dfn{port number} which distinguishes the
1024 sockets on a given machine (for a given protocol).  Port numbers range
1025 from 0 to 65,535.
1027 Port numbers less than @code{IPPORT_RESERVED} are reserved for standard
1028 servers, such as @code{finger} and @code{telnet}.  There is a database
1029 that keeps track of these, and you can use the @code{getservbyname}
1030 function to map a service name onto a port number; see @ref{Services
1031 Database}.
1033 If you write a server that is not one of the standard ones defined in
1034 the database, you must choose a port number for it.  Use a number
1035 greater than @code{IPPORT_USERRESERVED}; such numbers are reserved for
1036 servers and won't ever be generated automatically by the system.
1037 Avoiding conflicts with servers being run by other users is up to you.
1039 When you use a socket without specifying its address, the system
1040 generates a port number for it.  This number is between
1041 @code{IPPORT_RESERVED} and @code{IPPORT_USERRESERVED}.
1043 On the Internet, it is actually legitimate to have two different
1044 sockets with the same port number, as long as they never both try to
1045 communicate with the same socket address (host address plus port
1046 number).  You shouldn't duplicate a port number except in special
1047 circumstances where a higher-level protocol requires it.  Normally,
1048 the system won't let you do it; @code{bind} normally insists on
1049 distinct port numbers.  To reuse a port number, you must set the
1050 socket option @code{SO_REUSEADDR}.  @xref{Socket-Level Options}.
1052 @pindex netinet/in.h
1053 These macros are defined in the header file @file{netinet/in.h}.
1055 @comment netinet/in.h
1056 @comment BSD
1057 @deftypevr Macro int IPPORT_RESERVED
1058 Port numbers less than @code{IPPORT_RESERVED} are reserved for
1059 superuser use.
1060 @end deftypevr
1062 @comment netinet/in.h
1063 @comment BSD
1064 @deftypevr Macro int IPPORT_USERRESERVED
1065 Port numbers greater than or equal to @code{IPPORT_USERRESERVED} are
1066 reserved for explicit use; they will never be allocated automatically.
1067 @end deftypevr
1069 @node Services Database
1070 @subsection The Services Database
1071 @cindex services database
1072 @cindex converting service name to port number
1073 @cindex converting port number to service name
1075 @pindex /etc/services
1076 The database that keeps track of ``well-known'' services is usually
1077 either the file @file{/etc/services} or an equivalent from a name server.
1078 You can use these utilities, declared in @file{netdb.h}, to access
1079 the services database.
1080 @pindex netdb.h
1082 @comment netdb.h
1083 @comment BSD
1084 @deftp {Data Type} {struct servent}
1085 This data type holds information about entries from the services database.
1086 It has the following members:
1088 @table @code
1089 @item char *s_name
1090 This is the ``official'' name of the service.
1092 @item char **s_aliases
1093 These are alternate names for the service, represented as an array of
1094 strings.  A null pointer terminates the array.
1096 @item int s_port
1097 This is the port number for the service.  Port numbers are given in
1098 network byte order; see @ref{Byte Order}.
1100 @item char *s_proto
1101 This is the name of the protocol to use with this service.
1102 @xref{Protocols Database}.
1103 @end table
1104 @end deftp
1106 To get information about a particular service, use the
1107 @code{getservbyname} or @code{getservbyport} functions.  The information
1108 is returned in a statically-allocated structure; you must copy the
1109 information if you need to save it across calls.
1111 @comment netdb.h
1112 @comment BSD
1113 @deftypefun {struct servent *} getservbyname (const char *@var{name}, const char *@var{proto})
1114 The @code{getservbyname} function returns information about the
1115 service named @var{name} using protocol @var{proto}.  If it can't find
1116 such a service, it returns a null pointer.
1118 This function is useful for servers as well as for clients; servers
1119 use it to determine which port they should listen on (@pxref{Listening}).
1120 @end deftypefun
1122 @comment netdb.h
1123 @comment BSD
1124 @deftypefun {struct servent *} getservbyport (int @var{port}, const char *@var{proto})
1125 The @code{getservbyport} function returns information about the
1126 service at port @var{port} using protocol @var{proto}.  If it can't
1127 find such a service, it returns a null pointer.
1128 @end deftypefun
1130 You can also scan the services database using @code{setservent},
1131 @code{getservent}, and @code{endservent}.  Be careful in using these
1132 functions, because they are not reentrant.
1134 @comment netdb.h
1135 @comment BSD
1136 @deftypefun void setservent (int @var{stayopen})
1137 This function opens the services database to begin scanning it.
1139 If the @var{stayopen} argument is nonzero, this sets a flag so that
1140 subsequent calls to @code{getservbyname} or @code{getservbyport} will
1141 not close the database (as they usually would).  This makes for more
1142 efficiency if you call those functions several times, by avoiding
1143 reopening the database for each call.
1144 @end deftypefun
1146 @comment netdb.h
1147 @comment BSD
1148 @deftypefun {struct servent *} getservent (void)
1149 This function returns the next entry in the services database.  If
1150 there are no more entries, it returns a null pointer.
1151 @end deftypefun
1153 @comment netdb.h
1154 @comment BSD
1155 @deftypefun void endservent (void)
1156 This function closes the services database.
1157 @end deftypefun
1159 @node Byte Order
1160 @subsection Byte Order Conversion
1161 @cindex byte order conversion, for socket
1162 @cindex converting byte order
1164 @cindex big-endian
1165 @cindex little-endian
1166 Different kinds of computers use different conventions for the
1167 ordering of bytes within a word.  Some computers put the most
1168 significant byte within a word first (this is called ``big-endian''
1169 order), and others put it last (``little-endian'' order).
1171 @cindex network byte order
1172 So that machines with different byte order conventions can
1173 communicate, the Internet protocols specify a canonical byte order
1174 convention for data transmitted over the network.  This is known
1175 as the @dfn{network byte order}.
1177 When establishing an Internet socket connection, you must make sure that
1178 the data in the @code{sin_port} and @code{sin_addr} members of the
1179 @code{sockaddr_in} structure are represented in the network byte order.
1180 If you are encoding integer data in the messages sent through the
1181 socket, you should convert this to network byte order too.  If you don't
1182 do this, your program may fail when running on or talking to other kinds
1183 of machines.
1185 If you use @code{getservbyname} and @code{gethostbyname} or
1186 @code{inet_addr} to get the port number and host address, the values are
1187 already in the network byte order, and you can copy them directly into
1188 the @code{sockaddr_in} structure.
1190 Otherwise, you have to convert the values explicitly.  Use
1191 @code{htons} and @code{ntohs} to convert values for the @code{sin_port}
1192 member.  Use @code{htonl} and @code{ntohl} to convert values for the
1193 @code{sin_addr} member.  (Remember, @code{struct in_addr} is equivalent
1194 to @code{unsigned long int}.)  These functions are declared in
1195 @file{netinet/in.h}.
1196 @pindex netinet/in.h
1198 @comment netinet/in.h
1199 @comment BSD
1200 @deftypefun {unsigned short int} htons (unsigned short int @var{hostshort})
1201 This function converts the @code{short} integer @var{hostshort} from
1202 host byte order to network byte order.
1203 @end deftypefun
1205 @comment netinet/in.h
1206 @comment BSD
1207 @deftypefun {unsigned short int} ntohs (unsigned short int @var{netshort})
1208 This function converts the @code{short} integer @var{netshort} from
1209 network byte order to host byte order.
1210 @end deftypefun
1212 @comment netinet/in.h
1213 @comment BSD
1214 @deftypefun {unsigned long int} htonl (unsigned long int @var{hostlong})
1215 This function converts the @code{long} integer @var{hostlong} from
1216 host byte order to network byte order.
1217 @end deftypefun
1219 @comment netinet/in.h
1220 @comment BSD
1221 @deftypefun {unsigned long int} ntohl (unsigned long int @var{netlong})
1222 This function converts the @code{long} integer @var{netlong} from
1223 network byte order to host byte order.
1224 @end deftypefun
1226 @node Protocols Database
1227 @subsection Protocols Database
1228 @cindex protocols database
1230 The communications protocol used with a socket controls low-level
1231 details of how data is exchanged.  For example, the protocol implements
1232 things like checksums to detect errors in transmissions, and routing
1233 instructions for messages.  Normal user programs have little reason to
1234 mess with these details directly.
1236 @cindex TCP (Internet protocol)
1237 The default communications protocol for the Internet namespace depends on
1238 the communication style.  For stream communication, the default is TCP
1239 (``transmission control protocol'').  For datagram communication, the
1240 default is UDP (``user datagram protocol'').  For reliable datagram
1241 communication, the default is RDP (``reliable datagram protocol'').
1242 You should nearly always use the default.
1244 @pindex /etc/protocols
1245 Internet protocols are generally specified by a name instead of a
1246 number.  The network protocols that a host knows about are stored in a
1247 database.  This is usually either derived from the file
1248 @file{/etc/protocols}, or it may be an equivalent provided by a name
1249 server.  You look up the protocol number associated with a named
1250 protocol in the database using the @code{getprotobyname} function.
1252 Here are detailed descriptions of the utilities for accessing the
1253 protocols database.  These are declared in @file{netdb.h}.
1254 @pindex netdb.h
1256 @comment netdb.h
1257 @comment BSD
1258 @deftp {Data Type} {struct protoent}
1259 This data type is used to represent entries in the network protocols
1260 database.  It has the following members:
1262 @table @code
1263 @item char *p_name
1264 This is the official name of the protocol.
1266 @item char **p_aliases
1267 These are alternate names for the protocol, specified as an array of
1268 strings.  The last element of the array is a null pointer.
1270 @item int p_proto
1271 This is the protocol number (in host byte order); use this member as the
1272 @var{protocol} argument to @code{socket}.
1273 @end table
1274 @end deftp
1276 You can use @code{getprotobyname} and @code{getprotobynumber} to search
1277 the protocols database for a specific protocol.  The information is
1278 returned in a statically-allocated structure; you must copy the
1279 information if you need to save it across calls.
1281 @comment netdb.h
1282 @comment BSD
1283 @deftypefun {struct protoent *} getprotobyname (const char *@var{name})
1284 The @code{getprotobyname} function returns information about the
1285 network protocol named @var{name}.  If there is no such protocol, it
1286 returns a null pointer.
1287 @end deftypefun
1289 @comment netdb.h
1290 @comment BSD
1291 @deftypefun {struct protoent *} getprotobynumber (int @var{protocol})
1292 The @code{getprotobynumber} function returns information about the
1293 network protocol with number @var{protocol}.  If there is no such
1294 protocol, it returns a null pointer.
1295 @end deftypefun
1297 You can also scan the whole protocols database one protocol at a time by
1298 using @code{setprotoent}, @code{getprotoent}, and @code{endprotoent}.
1299 Be careful in using these functions, because they are not reentrant.
1301 @comment netdb.h
1302 @comment BSD
1303 @deftypefun void setprotoent (int @var{stayopen})
1304 This function opens the protocols database to begin scanning it.
1306 If the @var{stayopen} argument is nonzero, this sets a flag so that
1307 subsequent calls to @code{getprotobyname} or @code{getprotobynumber} will
1308 not close the database (as they usually would).  This makes for more
1309 efficiency if you call those functions several times, by avoiding
1310 reopening the database for each call.
1311 @end deftypefun
1313 @comment netdb.h
1314 @comment BSD
1315 @deftypefun {struct protoent *} getprotoent (void)
1316 This function returns the next entry in the protocols database.  It
1317 returns a null pointer if there are no more entries.
1318 @end deftypefun
1320 @comment netdb.h
1321 @comment BSD
1322 @deftypefun void endprotoent (void)
1323 This function closes the protocols database.
1324 @end deftypefun
1326 @node Inet Example
1327 @subsection Internet Socket Example
1329 Here is an example showing how to create and name a socket in the
1330 Internet namespace.  The newly created socket exists on the machine that
1331 the program is running on.  Rather than finding and using the machine's
1332 Internet address, this example specifies @code{INADDR_ANY} as the host
1333 address; the system replaces that with the machine's actual address.
1335 @smallexample
1336 @include mkisock.c.texi
1337 @end smallexample
1339 Here is another example, showing how you can fill in a @code{sockaddr_in}
1340 structure, given a host name string and a port number:
1342 @smallexample
1343 @include isockad.c.texi
1344 @end smallexample
1346 @node Misc Namespaces
1347 @section Other Namespaces
1349 @vindex PF_NS
1350 @vindex PF_ISO
1351 @vindex PF_CCITT
1352 @vindex PF_IMPLINK
1353 @vindex PF_ROUTE
1354 Certain other namespaces and associated protocol families are supported
1355 but not documented yet because they are not often used.  @code{PF_NS}
1356 refers to the Xerox Network Software protocols.  @code{PF_ISO} stands
1357 for Open Systems Interconnect.  @code{PF_CCITT} refers to protocols from
1358 CCITT.  @file{socket.h} defines these symbols and others naming protocols
1359 not actually implemented.
1361 @code{PF_IMPLINK} is used for communicating between hosts and Internet
1362 Message Processors.  For information on this, and on @code{PF_ROUTE}, an
1363 occasionally-used local area routing protocol, see the GNU Hurd Manual
1364 (to appear in the future).
1366 @node Open/Close Sockets
1367 @section Opening and Closing Sockets
1369 This section describes the actual library functions for opening and
1370 closing sockets.  The same functions work for all namespaces and
1371 connection styles.
1373 @menu
1374 * Creating a Socket::           How to open a socket.
1375 * Closing a Socket::            How to close a socket.
1376 * Socket Pairs::                These are created like pipes.
1377 @end menu
1379 @node Creating a Socket
1380 @subsection Creating a Socket
1381 @cindex creating a socket
1382 @cindex socket, creating
1383 @cindex opening a socket
1385 The primitive for creating a socket is the @code{socket} function,
1386 declared in @file{sys/socket.h}.
1387 @pindex sys/socket.h
1389 @comment sys/socket.h
1390 @comment BSD
1391 @deftypefun int socket (int @var{namespace}, int @var{style}, int @var{protocol})
1392 This function creates a socket and specifies communication style
1393 @var{style}, which should be one of the socket styles listed in
1394 @ref{Communication Styles}.  The @var{namespace} argument specifies
1395 the namespace; it must be @code{PF_FILE} (@pxref{File Namespace}) or
1396 @code{PF_INET} (@pxref{Internet Namespace}).  @var{protocol}
1397 designates the specific protocol (@pxref{Socket Concepts}); zero is
1398 usually right for @var{protocol}.
1400 The return value from @code{socket} is the file descriptor for the new
1401 socket, or @code{-1} in case of error.  The following @code{errno} error
1402 conditions are defined for this function:
1404 @table @code
1405 @item EPROTONOSUPPORT
1406 The @var{protocol} or @var{style} is not supported by the
1407 @var{namespace} specified.
1409 @item EMFILE
1410 The process already has too many file descriptors open.
1412 @item ENFILE
1413 The system already has too many file descriptors open.
1415 @item EACCESS
1416 The process does not have privilege to create a socket of the specified
1417 @var{style} or @var{protocol}.
1419 @item ENOBUFS
1420 The system ran out of internal buffer space.
1421 @end table
1423 The file descriptor returned by the @code{socket} function supports both
1424 read and write operations.  But, like pipes, sockets do not support file
1425 positioning operations.
1426 @end deftypefun
1428 For examples of how to call the @code{socket} function,
1429 see @ref{File Namespace}, or @ref{Inet Example}.
1432 @node Closing a Socket
1433 @subsection Closing a Socket
1434 @cindex socket, closing
1435 @cindex closing a socket
1436 @cindex shutting down a socket
1437 @cindex socket shutdown
1439 When you are finished using a socket, you can simply close its
1440 file descriptor with @code{close}; see @ref{Opening and Closing Files}.
1441 If there is still data waiting to be transmitted over the connection,
1442 normally @code{close} tries to complete this transmission.  You
1443 can control this behavior using the @code{SO_LINGER} socket option to
1444 specify a timeout period; see @ref{Socket Options}.
1446 @pindex sys/socket.h
1447 You can also shut down only reception or only transmission on a
1448 connection by calling @code{shutdown}, which is declared in
1449 @file{sys/socket.h}.
1451 @comment sys/socket.h
1452 @comment BSD
1453 @deftypefun int shutdown (int @var{socket}, int @var{how})
1454 The @code{shutdown} function shuts down the connection of socket
1455 @var{socket}.  The argument @var{how} specifies what action to
1456 perform:
1458 @table @code
1459 @item 0
1460 Stop receiving data for this socket.  If further data arrives,
1461 reject it.
1463 @item 1
1464 Stop trying to transmit data from this socket.  Discard any data
1465 waiting to be sent.  Stop looking for acknowledgement of data already
1466 sent; don't retransmit it if it is lost.
1468 @item 2
1469 Stop both reception and transmission.
1470 @end table
1472 The return value is @code{0} on success and @code{-1} on failure.  The
1473 following @code{errno} error conditions are defined for this function:
1475 @table @code
1476 @item EBADF
1477 @var{socket} is not a valid file descriptor.
1479 @item ENOTSOCK
1480 @var{socket} is not a socket.
1482 @item ENOTCONN
1483 @var{socket} is not connected.
1484 @end table
1485 @end deftypefun
1487 @node Socket Pairs
1488 @subsection Socket Pairs
1489 @cindex creating a socket pair
1490 @cindex socket pair
1491 @cindex opening a socket pair
1493 @pindex sys/socket.h
1494 A @dfn{socket pair} consists of a pair of connected (but unnamed)
1495 sockets.  It is very similar to a pipe and is used in much the same
1496 way.  Socket pairs are created with the @code{socketpair} function,
1497 declared in @file{sys/socket.h}.  A socket pair is much like a pipe; the
1498 main difference is that the socket pair is bidirectional, whereas the
1499 pipe has one input-only end and one output-only end (@pxref{Pipes and
1500 FIFOs}).
1502 @comment sys/socket.h
1503 @comment BSD
1504 @deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})
1505 This function creates a socket pair, returning the file descriptors in
1506 @code{@var{filedes}[0]} and @code{@var{filedes}[1]}.  The socket pair
1507 is a full-duplex communications channel, so that both reading and writing
1508 may be performed at either end.
1510 The @var{namespace}, @var{style}, and @var{protocol} arguments are
1511 interpreted as for the @code{socket} function.  @var{style} should be
1512 one of the communication styles listed in @ref{Communication Styles}.
1513 The @var{namespace} argument specifies the namespace, which must be
1514 @code{AF_FILE} (@pxref{File Namespace}); @var{protocol} specifies the
1515 communications protocol, but zero is the only meaningful value.
1517 If @var{style} specifies a connectionless communication style, then
1518 the two sockets you get are not @emph{connected}, strictly speaking,
1519 but each of them knows the other as the default destination address,
1520 so they can send packets to each other.
1522 The @code{socketpair} function returns @code{0} on success and @code{-1}
1523 on failure.  The following @code{errno} error conditions are defined
1524 for this function:
1526 @table @code
1527 @item EMFILE
1528 The process has too many file descriptors open.
1530 @item EAFNOSUPPORT
1531 The specified namespace is not supported.
1533 @item EPROTONOSUPPORT
1534 The specified protocol is not supported.
1536 @item EOPNOTSUPP
1537 The specified protocol does not support the creation of socket pairs.
1538 @end table
1539 @end deftypefun
1541 @node Connections
1542 @section Using Sockets with Connections
1544 @cindex connection
1545 @cindex client
1546 @cindex server
1547 The most common communication styles involve making a connection to a
1548 particular other socket, and then exchanging data with that socket
1549 over and over.  Making a connection is asymmetric; one side (the
1550 @dfn{client}) acts to request a connection, while the other side (the
1551 @dfn{server}) makes a socket and waits for the connection request.
1553 @iftex
1554 @itemize @bullet
1555 @item
1556 @ref{Connecting}, describes what the client program must do to
1557 initiate a connection with a server.
1559 @item
1560 @ref{Listening}, and @ref{Accepting Connections}, describe what the
1561 server program must do to wait for and act upon connection requests
1562 from clients.
1564 @item
1565 @ref{Transferring Data}, describes how data is transferred through the
1566 connected socket.
1567 @end itemize
1568 @end iftex
1570 @menu
1571 * Connecting::               What the client program must do.
1572 * Listening::                How a server program waits for requests.
1573 * Accepting Connections::    What the server does when it gets a request.
1574 * Who is Connected::         Getting the address of the
1575                                 other side of a connection.
1576 * Transferring Data::        How to send and receive data.
1577 * Byte Stream Example::      An example program: a client for communicating
1578                               over a byte stream socket in the Internet namespace.
1579 * Server Example::           A corresponding server program.
1580 * Out-of-Band Data::         This is an advanced feature.
1581 @end menu
1583 @node Connecting
1584 @subsection Making a Connection
1585 @cindex connecting a socket
1586 @cindex socket, connecting
1587 @cindex socket, initiating a connection
1588 @cindex socket, client actions
1590 In making a connection, the client makes a connection while the server
1591 waits for and accepts the connection.  Here we discuss what the client
1592 program must do, using the @code{connect} function, which is declared in
1593 @file{sys/socket.h}.
1595 @comment sys/socket.h
1596 @comment BSD
1597 @deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, size_t @var{length})
1598 The @code{connect} function initiates a connection from the socket
1599 with file descriptor @var{socket} to the socket whose address is
1600 specified by the @var{addr} and @var{length} arguments.  (This socket
1601 is typically on another machine, and it must be already set up as a
1602 server.)  @xref{Socket Addresses}, for information about how these
1603 arguments are interpreted.
1605 Normally, @code{connect} waits until the server responds to the request
1606 before it returns.  You can set nonblocking mode on the socket
1607 @var{socket} to make @code{connect} return immediately without waiting
1608 for the response.  @xref{File Status Flags}, for information about
1609 nonblocking mode.
1610 @c !!! how do you tell when it has finished connecting?  I suspect the
1611 @c way you do it is select for writing.
1613 The normal return value from @code{connect} is @code{0}.  If an error
1614 occurs, @code{connect} returns @code{-1}.  The following @code{errno}
1615 error conditions are defined for this function:
1617 @table @code
1618 @item EBADF
1619 The socket @var{socket} is not a valid file descriptor.
1621 @item ENOTSOCK
1622 File descriptor @var{socket} is not a socket.
1624 @item EADDRNOTAVAIL
1625 The specified address is not available on the remote machine.
1627 @item EAFNOSUPPORT
1628 The namespace of the @var{addr} is not supported by this socket.
1630 @item EISCONN
1631 The socket @var{socket} is already connected.
1633 @item ETIMEDOUT
1634 The attempt to establish the connection timed out.
1636 @item ECONNREFUSED
1637 The server has actively refused to establish the connection.
1639 @item ENETUNREACH
1640 The network of the given @var{addr} isn't reachable from this host.
1642 @item EADDRINUSE
1643 The socket address of the given @var{addr} is already in use.
1645 @item EINPROGRESS
1646 The socket @var{socket} is non-blocking and the connection could not be
1647 established immediately.  You can determine when the connection is
1648 completely established with @code{select}; @pxref{Waiting for I/O}.
1649 Another @code{connect} call on the same socket, before the connection is
1650 completely established, will fail with @code{EALREADY}.
1652 @item EALREADY
1653 The socket @var{socket} is non-blocking and already has a pending
1654 connection in progress (see @code{EINPROGRESS} above).
1655 @end table
1656 @end deftypefun
1658 @node Listening
1659 @subsection Listening for Connections
1660 @cindex listening (sockets)
1661 @cindex sockets, server actions
1662 @cindex sockets, listening
1664 Now let us consider what the server process must do to accept
1665 connections on a socket.  First it must use the @code{listen} function
1666 to enable connection requests on the socket, and then accept each
1667 incoming connection with a call to @code{accept} (@pxref{Accepting
1668 Connections}).  Once connection requests are enabled on a server socket,
1669 the @code{select} function reports when the socket has a connection
1670 ready to be accepted (@pxref{Waiting for I/O}).
1672 The @code{listen} function is not allowed for sockets using
1673 connectionless communication styles.
1675 You can write a network server that does not even start running until a
1676 connection to it is requested.  @xref{Inetd Servers}.
1678 In the Internet namespace, there are no special protection mechanisms
1679 for controlling access to connect to a port; any process on any machine
1680 can make a connection to your server.  If you want to restrict access to
1681 your server, make it examine the addresses associated with connection
1682 requests or implement some other handshaking or identification
1683 protocol.
1685 In the File namespace, the ordinary file protection bits control who has
1686 access to connect to the socket.
1688 @comment sys/socket.h
1689 @comment BSD
1690 @deftypefun int listen (int @var{socket}, unsigned int @var{n})
1691 The @code{listen} function enables the socket @var{socket} to accept
1692 connections, thus making it a server socket.
1694 The argument @var{n} specifies the length of the queue for pending
1695 connections.  When the queue fills, new clients attempting to connect
1696 fail with @code{ECONNREFUSED} until the server calls @code{accept} to
1697 accept a connection from the queue.
1699 The @code{listen} function returns @code{0} on success and @code{-1}
1700 on failure.  The following @code{errno} error conditions are defined
1701 for this function:
1703 @table @code
1704 @item EBADF
1705 The argument @var{socket} is not a valid file descriptor.
1707 @item ENOTSOCK
1708 The argument @var{socket} is not a socket.
1710 @item EOPNOTSUPP
1711 The socket @var{socket} does not support this operation.
1712 @end table
1713 @end deftypefun
1715 @node Accepting Connections
1716 @subsection Accepting Connections
1717 @cindex sockets, accepting connections
1718 @cindex accepting connections
1720 When a server receives a connection request, it can complete the
1721 connection by accepting the request.  Use the function @code{accept}
1722 to do this.
1724 A socket that has been established as a server can accept connection
1725 requests from multiple clients.  The server's original socket
1726 @emph{does not become part} of the connection; instead, @code{accept}
1727 makes a new socket which participates in the connection.
1728 @code{accept} returns the descriptor for this socket.  The server's
1729 original socket remains available for listening for further connection
1730 requests.
1732 The number of pending connection requests on a server socket is finite.
1733 If connection requests arrive from clients faster than the server can
1734 act upon them, the queue can fill up and additional requests are refused
1735 with a @code{ECONNREFUSED} error.  You can specify the maximum length of
1736 this queue as an argument to the @code{listen} function, although the
1737 system may also impose its own internal limit on the length of this
1738 queue.
1740 @comment sys/socket.h
1741 @comment BSD
1742 @deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
1743 This function is used to accept a connection request on the server
1744 socket @var{socket}.
1746 The @code{accept} function waits if there are no connections pending,
1747 unless the socket @var{socket} has nonblocking mode set.  (You can use
1748 @code{select} to wait for a pending connection, with a nonblocking
1749 socket.)  @xref{File Status Flags}, for information about nonblocking
1750 mode.
1752 The @var{addr} and @var{length-ptr} arguments are used to return
1753 information about the name of the client socket that initiated the
1754 connection.  @xref{Socket Addresses}, for information about the format
1755 of the information.
1757 Accepting a connection does not make @var{socket} part of the
1758 connection.  Instead, it creates a new socket which becomes
1759 connected.  The normal return value of @code{accept} is the file
1760 descriptor for the new socket.
1762 After @code{accept}, the original socket @var{socket} remains open and
1763 unconnected, and continues listening until you close it.  You can
1764 accept further connections with @var{socket} by calling @code{accept}
1765 again.
1767 If an error occurs, @code{accept} returns @code{-1}.  The following
1768 @code{errno} error conditions are defined for this function:
1770 @table @code
1771 @item EBADF
1772 The @var{socket} argument is not a valid file descriptor.
1774 @item ENOTSOCK
1775 The descriptor @var{socket} argument is not a socket.
1777 @item EOPNOTSUPP
1778 The descriptor @var{socket} does not support this operation.
1780 @item EWOULDBLOCK
1781 @var{socket} has nonblocking mode set, and there are no pending
1782 connections immediately available.
1783 @end table
1784 @end deftypefun
1786 The @code{accept} function is not allowed for sockets using
1787 connectionless communication styles.
1789 @node Who is Connected
1790 @subsection Who is Connected to Me?
1792 @comment sys/socket.h
1793 @comment BSD
1794 @deftypefun int getpeername (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
1795 The @code{getpeername} function returns the address of the socket that
1796 @var{socket} is connected to; it stores the address in the memory space
1797 specified by @var{addr} and @var{length-ptr}.  It stores the length of
1798 the address in @code{*@var{length-ptr}}.
1800 @xref{Socket Addresses}, for information about the format of the
1801 address.  In some operating systems, @code{getpeername} works only for
1802 sockets in the Internet domain.
1804 The return value is @code{0} on success and @code{-1} on error.  The
1805 following @code{errno} error conditions are defined for this function:
1807 @table @code
1808 @item EBADF
1809 The argument @var{socket} is not a valid file descriptor.
1811 @item ENOTSOCK
1812 The descriptor @var{socket} is not a socket.
1814 @item ENOTCONN
1815 The socket @var{socket} is not connected.
1817 @item ENOBUFS
1818 There are not enough internal buffers available.
1819 @end table
1820 @end deftypefun
1823 @node Transferring Data
1824 @subsection Transferring Data
1825 @cindex reading from a socket
1826 @cindex writing to a socket
1828 Once a socket has been connected to a peer, you can use the ordinary
1829 @code{read} and @code{write} operations (@pxref{I/O Primitives}) to
1830 transfer data.  A socket is a two-way communications channel, so read
1831 and write operations can be performed at either end.
1833 There are also some I/O modes that are specific to socket operations.
1834 In order to specify these modes, you must use the @code{recv} and
1835 @code{send} functions instead of the more generic @code{read} and
1836 @code{write} functions.  The @code{recv} and @code{send} functions take
1837 an additional argument which you can use to specify various flags to
1838 control the special I/O modes.  For example, you can specify the
1839 @code{MSG_OOB} flag to read or write out-of-band data, the
1840 @code{MSG_PEEK} flag to peek at input, or the @code{MSG_DONTROUTE} flag
1841 to control inclusion of routing information on output.
1843 @menu
1844 * Sending Data::                Sending data with @code{send}.
1845 * Receiving Data::              Reading data with @code{recv}.
1846 * Socket Data Options::         Using @code{send} and @code{recv}.
1847 @end menu
1849 @node Sending Data
1850 @subsubsection Sending Data
1852 @pindex sys/socket.h
1853 The @code{send} function is declared in the header file
1854 @file{sys/socket.h}.  If your @var{flags} argument is zero, you can just
1855 as well use @code{write} instead of @code{send}; see @ref{I/O
1856 Primitives}.  If the socket was connected but the connection has broken,
1857 you get a @code{SIGPIPE} signal for any use of @code{send} or
1858 @code{write} (@pxref{Miscellaneous Signals}).
1860 @comment sys/socket.h
1861 @comment BSD
1862 @deftypefun int send (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
1863 The @code{send} function is like @code{write}, but with the additional
1864 flags @var{flags}.  The possible values of @var{flags} are described
1865 in @ref{Socket Data Options}.
1867 This function returns the number of bytes transmitted, or @code{-1} on
1868 failure.  If the socket is nonblocking, then @code{send} (like
1869 @code{write}) can return after sending just part of the data.
1870 @xref{File Status Flags}, for information about nonblocking mode.
1872 Note, however, that a successful return value merely indicates that
1873 the message has been sent without error, not necessarily that it has
1874 been received without error.
1876 The following @code{errno} error conditions are defined for this function:
1878 @table @code
1879 @item EBADF
1880 The @var{socket} argument is not a valid file descriptor.
1882 @item EINTR
1883 The operation was interrupted by a signal before any data was sent.
1884 @xref{Interrupted Primitives}.
1886 @item ENOTSOCK
1887 The descriptor @var{socket} is not a socket.
1889 @item EMSGSIZE
1890 The socket type requires that the message be sent atomically, but the
1891 message is too large for this to be possible.
1893 @item EWOULDBLOCK
1894 Nonblocking mode has been set on the socket, and the write operation
1895 would block.  (Normally @code{send} blocks until the operation can be
1896 completed.)
1898 @item ENOBUFS
1899 There is not enough internal buffer space available.
1901 @item ENOTCONN
1902 You never connected this socket.
1904 @item EPIPE
1905 This socket was connected but the connection is now broken.  In this
1906 case, @code{send} generates a @code{SIGPIPE} signal first; if that
1907 signal is ignored or blocked, or if its handler returns, then
1908 @code{send} fails with @code{EPIPE}.
1909 @end table
1910 @end deftypefun
1912 @node Receiving Data
1913 @subsubsection Receiving Data
1915 @pindex sys/socket.h
1916 The @code{recv} function is declared in the header file
1917 @file{sys/socket.h}.  If your @var{flags} argument is zero, you can
1918 just as well use @code{read} instead of @code{recv}; see @ref{I/O
1919 Primitives}.
1921 @comment sys/socket.h
1922 @comment BSD
1923 @deftypefun int recv (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
1924 The @code{recv} function is like @code{read}, but with the additional
1925 flags @var{flags}.  The possible values of @var{flags} are described
1926 In @ref{Socket Data Options}.
1928 If nonblocking mode is set for @var{socket}, and no data is available to
1929 be read, @code{recv} fails immediately rather than waiting.  @xref{File
1930 Status Flags}, for information about nonblocking mode.
1932 This function returns the number of bytes received, or @code{-1} on failure.
1933 The following @code{errno} error conditions are defined for this function:
1935 @table @code
1936 @item EBADF
1937 The @var{socket} argument is not a valid file descriptor.
1939 @item ENOTSOCK
1940 The descriptor @var{socket} is not a socket.
1942 @item EWOULDBLOCK
1943 Nonblocking mode has been set on the socket, and the read operation
1944 would block.  (Normally, @code{recv} blocks until there is input
1945 available to be read.)
1947 @item EINTR
1948 The operation was interrupted by a signal before any data was read.
1949 @xref{Interrupted Primitives}.
1951 @item ENOTCONN
1952 You never connected this socket.
1953 @end table
1954 @end deftypefun
1956 @node Socket Data Options
1957 @subsubsection Socket Data Options
1959 @pindex sys/socket.h
1960 The @var{flags} argument to @code{send} and @code{recv} is a bit
1961 mask.  You can bitwise-OR the values of the following macros together
1962 to obtain a value for this argument.  All are defined in the header
1963 file @file{sys/socket.h}.
1965 @comment sys/socket.h
1966 @comment BSD
1967 @deftypevr Macro int MSG_OOB
1968 Send or receive out-of-band data.  @xref{Out-of-Band Data}.
1969 @end deftypevr
1971 @comment sys/socket.h
1972 @comment BSD
1973 @deftypevr Macro int MSG_PEEK
1974 Look at the data but don't remove it from the input queue.  This is
1975 only meaningful with input functions such as @code{recv}, not with
1976 @code{send}.
1977 @end deftypevr
1979 @comment sys/socket.h
1980 @comment BSD
1981 @deftypevr Macro int MSG_DONTROUTE
1982 Don't include routing information in the message.  This is only
1983 meaningful with output operations, and is usually only of interest for
1984 diagnostic or routing programs.  We don't try to explain it here.
1985 @end deftypevr
1987 @node Byte Stream Example
1988 @subsection Byte Stream Socket Example
1990 Here is an example client program that makes a connection for a byte
1991 stream socket in the Internet namespace.  It doesn't do anything
1992 particularly interesting once it has connected to the server; it just
1993 sends a text string to the server and exits.
1995 @smallexample
1996 @include inetcli.c.texi
1997 @end smallexample
1999 @node Server Example
2000 @subsection Byte Stream Connection Server Example
2002 The server end is much more complicated.  Since we want to allow
2003 multiple clients to be connected to the server at the same time, it
2004 would be incorrect to wait for input from a single client by simply
2005 calling @code{read} or @code{recv}.  Instead, the right thing to do is
2006 to use @code{select} (@pxref{Waiting for I/O}) to wait for input on
2007 all of the open sockets.  This also allows the server to deal with
2008 additional connection requests.
2010 This particular server doesn't do anything interesting once it has
2011 gotten a message from a client.  It does close the socket for that
2012 client when it detects an end-of-file condition (resulting from the
2013 client shutting down its end of the connection).
2015 This program uses @code{make_socket} and @code{init_sockaddr} to set
2016 up the socket address; see @ref{Inet Example}.
2018 @smallexample
2019 @include inetsrv.c.texi
2020 @end smallexample
2022 @node Out-of-Band Data
2023 @subsection Out-of-Band Data
2025 @cindex out-of-band data
2026 @cindex high-priority data
2027 Streams with connections permit @dfn{out-of-band} data that is
2028 delivered with higher priority than ordinary data.  Typically the
2029 reason for sending out-of-band data is to send notice of an
2030 exceptional condition.  The way to send out-of-band data is using
2031 @code{send}, specifying the flag @code{MSG_OOB} (@pxref{Sending
2032 Data}).
2034 Out-of-band data is received with higher priority because the
2035 receiving process need not read it in sequence; to read the next
2036 available out-of-band data, use @code{recv} with the @code{MSG_OOB}
2037 flag (@pxref{Receiving Data}).  Ordinary read operations do not read
2038 out-of-band data; they read only the ordinary data.
2040 @cindex urgent socket condition
2041 When a socket finds that out-of-band data is on its way, it sends a
2042 @code{SIGURG} signal to the owner process or process group of the
2043 socket.  You can specify the owner using the @code{F_SETOWN} command
2044 to the @code{fcntl} function; see @ref{Interrupt Input}.  You must
2045 also establish a handler for this signal, as described in @ref{Signal
2046 Handling}, in order to take appropriate action such as reading the
2047 out-of-band data.
2049 Alternatively, you can test for pending out-of-band data, or wait
2050 until there is out-of-band data, using the @code{select} function; it
2051 can wait for an exceptional condition on the socket.  @xref{Waiting
2052 for I/O}, for more information about @code{select}.
2054 Notification of out-of-band data (whether with @code{SIGURG} or with
2055 @code{select}) indicates that out-of-band data is on the way; the data
2056 may not actually arrive until later.  If you try to read the
2057 out-of-band data before it arrives, @code{recv} fails with an
2058 @code{EWOULDBLOCK} error.
2060 Sending out-of-band data automatically places a ``mark'' in the stream
2061 of ordinary data, showing where in the sequence the out-of-band data
2062 ``would have been''.  This is useful when the meaning of out-of-band
2063 data is ``cancel everything sent so far''.  Here is how you can test,
2064 in the receiving process, whether any ordinary data was sent before
2065 the mark:
2067 @smallexample
2068 success = ioctl (socket, SIOCATMARK, &result);
2069 @end smallexample
2071 Here's a function to discard any ordinary data preceding the
2072 out-of-band mark:
2074 @smallexample
2076 discard_until_mark (int socket)
2078   while (1)
2079     @{
2080       /* @r{This is not an arbitrary limit; any size will do.}  */
2081       char buffer[1024];
2082       int result, success;
2084       /* @r{If we have reached the mark, return.}  */
2085       success = ioctl (socket, SIOCATMARK, &result);
2086       if (success < 0)
2087         perror ("ioctl");
2088       if (result)
2089         return;
2091       /* @r{Otherwise, read a bunch of ordinary data and discard it.}
2092          @r{This is guaranteed not to read past the mark}
2093          @r{if it starts before the mark.}  */
2094       success = read (socket, buffer, sizeof buffer);
2095       if (success < 0)
2096         perror ("read");
2097     @}
2099 @end smallexample
2101 If you don't want to discard the ordinary data preceding the mark, you
2102 may need to read some of it anyway, to make room in internal system
2103 buffers for the out-of-band data.  If you try to read out-of-band data
2104 and get an @code{EWOULDBLOCK} error, try reading some ordinary data
2105 (saving it so that you can use it when you want it) and see if that
2106 makes room.  Here is an example:
2108 @smallexample
2109 struct buffer
2111   char *buffer;
2112   int size;
2113   struct buffer *next;
2116 /* @r{Read the out-of-band data from SOCKET and return it}
2117    @r{as a `struct buffer', which records the address of the data}
2118    @r{and its size.}
2120    @r{It may be necessary to read some ordinary data}
2121    @r{in order to make room for the out-of-band data.}
2122    @r{If so, the ordinary data is saved as a chain of buffers}
2123    @r{found in the `next' field of the value.}  */
2125 struct buffer *
2126 read_oob (int socket)
2128   struct buffer *tail = 0;
2129   struct buffer *list = 0;
2131   while (1)
2132     @{
2133       /* @r{This is an arbitrary limit.}
2134          @r{Does anyone know how to do this without a limit?}  */
2135       char *buffer = (char *) xmalloc (1024);
2136       struct buffer *link;
2137       int success;
2138       int result;
2140       /* @r{Try again to read the out-of-band data.}  */
2141       success = recv (socket, buffer, sizeof buffer, MSG_OOB);
2142       if (success >= 0)
2143         @{
2144           /* @r{We got it, so return it.}  */
2145           struct buffer *link
2146             = (struct buffer *) xmalloc (sizeof (struct buffer));
2147           link->buffer = buffer;
2148           link->size = success;
2149           link->next = list;
2150           return link;
2151         @}
2153       /* @r{If we fail, see if we are at the mark.}  */
2154       success = ioctl (socket, SIOCATMARK, &result);
2155       if (success < 0)
2156         perror ("ioctl");
2157       if (result)
2158         @{
2159           /* @r{At the mark; skipping past more ordinary data cannot help.}
2160              @r{So just wait a while.}  */
2161           sleep (1);
2162           continue;
2163         @}
2165       /* @r{Otherwise, read a bunch of ordinary data and save it.}
2166          @r{This is guaranteed not to read past the mark}
2167          @r{if it starts before the mark.}  */
2168       success = read (socket, buffer, sizeof buffer);
2169       if (success < 0)
2170         perror ("read");
2172       /* @r{Save this data in the buffer list.}  */
2173       @{
2174         struct buffer *link
2175           = (struct buffer *) xmalloc (sizeof (struct buffer));
2176         link->buffer = buffer;
2177         link->size = success;
2179         /* @r{Add the new link to the end of the list.}  */
2180         if (tail)
2181           tail->next = link;
2182         else
2183           list = link;
2184         tail = link;
2185       @}
2186     @}
2188 @end smallexample
2190 @node Datagrams
2191 @section Datagram Socket Operations
2193 @cindex datagram socket
2194 This section describes how to use communication styles that don't use
2195 connections (styles @code{SOCK_DGRAM} and @code{SOCK_RDM}).  Using
2196 these styles, you group data into packets and each packet is an
2197 independent communication.  You specify the destination for each
2198 packet individually.
2200 Datagram packets are like letters: you send each one independently,
2201 with its own destination address, and they may arrive in the wrong
2202 order or not at all.
2204 The @code{listen} and @code{accept} functions are not allowed for
2205 sockets using connectionless communication styles.
2207 @menu
2208 * Sending Datagrams::    Sending packets on a datagram socket.
2209 * Receiving Datagrams::  Receiving packets on a datagram socket.
2210 * Datagram Example::     An example program: packets sent over a
2211                            datagram socket in the file namespace.
2212 * Example Receiver::     Another program, that receives those packets.
2213 @end menu
2215 @node Sending Datagrams
2216 @subsection Sending Datagrams
2217 @cindex sending a datagram
2218 @cindex transmitting datagrams
2219 @cindex datagrams, transmitting
2221 @pindex sys/socket.h
2222 The normal way of sending data on a datagram socket is by using the
2223 @code{sendto} function, declared in @file{sys/socket.h}.
2225 You can call @code{connect} on a datagram socket, but this only
2226 specifies a default destination for further data transmission on the
2227 socket.  When a socket has a default destination, then you can use
2228 @code{send} (@pxref{Sending Data}) or even @code{write} (@pxref{I/O
2229 Primitives}) to send a packet there.  You can cancel the default
2230 destination by calling @code{connect} using an address format of
2231 @code{AF_UNSPEC} in the @var{addr} argument.  @xref{Connecting}, for
2232 more information about the @code{connect} function.
2234 @comment sys/socket.h
2235 @comment BSD
2236 @deftypefun int sendto (int @var{socket}, void *@var{buffer}. size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, size_t @var{length})
2237 The @code{sendto} function transmits the data in the @var{buffer}
2238 through the socket @var{socket} to the destination address specified
2239 by the @var{addr} and @var{length} arguments.  The @var{size} argument
2240 specifies the number of bytes to be transmitted.
2242 The @var{flags} are interpreted the same way as for @code{send}; see
2243 @ref{Socket Data Options}.
2245 The return value and error conditions are also the same as for
2246 @code{send}, but you cannot rely on the system to detect errors and
2247 report them; the most common error is that the packet is lost or there
2248 is no one at the specified address to receive it, and the operating
2249 system on your machine usually does not know this.
2251 It is also possible for one call to @code{sendto} to report an error
2252 due to a problem related to a previous call.
2253 @end deftypefun
2255 @node Receiving Datagrams
2256 @subsection Receiving Datagrams
2257 @cindex receiving datagrams
2259 The @code{recvfrom} function reads a packet from a datagram socket and
2260 also tells you where it was sent from.  This function is declared in
2261 @file{sys/socket.h}.
2263 @comment sys/socket.h
2264 @comment BSD
2265 @deftypefun int recvfrom (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
2266 The @code{recvfrom} function reads one packet from the socket
2267 @var{socket} into the buffer @var{buffer}.  The @var{size} argument
2268 specifies the maximum number of bytes to be read.
2270 If the packet is longer than @var{size} bytes, then you get the first
2271 @var{size} bytes of the packet, and the rest of the packet is lost.
2272 There's no way to read the rest of the packet.  Thus, when you use a
2273 packet protocol, you must always know how long a packet to expect.
2275 The @var{addr} and @var{length-ptr} arguments are used to return the
2276 address where the packet came from.  @xref{Socket Addresses}.  For a
2277 socket in the file domain, the address information won't be meaningful,
2278 since you can't read the address of such a socket (@pxref{File
2279 Namespace}).  You can specify a null pointer as the @var{addr} argument
2280 if you are not interested in this information.
2282 The @var{flags} are interpreted the same way as for @code{recv}
2283 (@pxref{Socket Data Options}).  The return value and error conditions
2284 are also the same as for @code{recv}.
2285 @end deftypefun
2287 You can use plain @code{recv} (@pxref{Receiving Data}) instead of
2288 @code{recvfrom} if you know don't need to find out who sent the packet
2289 (either because you know where it should come from or because you
2290 treat all possible senders alike).  Even @code{read} can be used if
2291 you don't want to specify @var{flags} (@pxref{I/O Primitives}).
2293 @ignore
2294 @c sendmsg and recvmsg are like readv and writev in that they
2295 @c use a series of buffers.  It's not clear this is worth
2296 @c supporting or that we support them.
2297 @c !!! they can do more; it is hairy
2299 @comment sys/socket.h
2300 @comment BSD
2301 @deftp {Data Type} {struct msghdr}
2302 @end deftp
2304 @comment sys/socket.h
2305 @comment BSD
2306 @deftypefun int sendmsg (int @var{socket}, const struct msghdr *@var{message}, int @var{flags})
2307 @end deftypefun
2309 @comment sys/socket.h
2310 @comment BSD
2311 @deftypefun int recvmsg (int @var{socket}, struct msghdr *@var{message}, int @var{flags})
2312 @end deftypefun
2313 @end ignore
2315 @node Datagram Example
2316 @subsection Datagram Socket Example
2318 Here is a set of example programs that send messages over a datagram
2319 stream in the file namespace.  Both the client and server programs use the
2320 @code{make_named_socket} function that was presented in @ref{File
2321 Namespace}, to create and name their sockets.
2323 First, here is the server program.  It sits in a loop waiting for
2324 messages to arrive, bouncing each message back to the sender.
2325 Obviously, this isn't a particularly useful program, but it does show
2326 the general ideas involved.
2328 @smallexample
2329 @include filesrv.c.texi
2330 @end smallexample
2332 @node Example Receiver
2333 @subsection Example of Reading Datagrams
2335 Here is the client program corresponding to the server above.
2337 It sends a datagram to the server and then waits for a reply.  Notice
2338 that the socket for the client (as well as for the server) in this
2339 example has to be given a name.  This is so that the server can direct
2340 a message back to the client.  Since the socket has no associated
2341 connection state, the only way the server can do this is by
2342 referencing the name of the client.
2344 @smallexample
2345 @include filecli.c.texi
2346 @end smallexample
2348 Keep in mind that datagram socket communications are unreliable.  In
2349 this example, the client program waits indefinitely if the message
2350 never reaches the server or if the server's response never comes
2351 back.  It's up to the user running the program to kill it and restart
2352 it, if desired.  A more automatic solution could be to use
2353 @code{select} (@pxref{Waiting for I/O}) to establish a timeout period
2354 for the reply, and in case of timeout either resend the message or
2355 shut down the socket and exit.
2357 @node Inetd
2358 @section The @code{inetd} Daemon
2360 We've explained above how to write a server program that does its own
2361 listening.  Such a server must already be running in order for anyone
2362 to connect to it.
2364 Another way to provide service for an Internet port is to let the daemon
2365 program @code{inetd} do the listening.  @code{inetd} is a program that
2366 runs all the time and waits (using @code{select}) for messages on a
2367 specified set of ports.  When it receives a message, it accepts the
2368 connection (if the socket style calls for connections) and then forks a
2369 child process to run the corresponding server program.  You specify the
2370 ports and their programs in the file @file{/etc/inetd.conf}.
2372 @menu
2373 * Inetd Servers::
2374 * Configuring Inetd::
2375 @end menu
2377 @node Inetd Servers
2378 @subsection @code{inetd} Servers
2380 Writing a server program to be run by @code{inetd} is very simple.  Each time
2381 someone requests a connection to the appropriate port, a new server
2382 process starts.  The connection already exists at this time; the
2383 socket is available as the standard input descriptor and as the
2384 standard output descriptor (descriptors 0 and 1) in the server
2385 process.  So the server program can begin reading and writing data
2386 right away.  Often the program needs only the ordinary I/O facilities;
2387 in fact, a general-purpose filter program that knows nothing about
2388 sockets can work as a byte stream server run by @code{inetd}.
2390 You can also use @code{inetd} for servers that use connectionless
2391 communication styles.  For these servers, @code{inetd} does not try to accept
2392 a connection, since no connection is possible.  It just starts the
2393 server program, which can read the incoming datagram packet from
2394 descriptor 0.  The server program can handle one request and then
2395 exit, or you can choose to write it to keep reading more requests
2396 until no more arrive, and then exit.  You must specify which of these
2397 two techniques the server uses, when you configure @code{inetd}.
2399 @node Configuring Inetd
2400 @subsection Configuring @code{inetd}
2402 The file @file{/etc/inetd.conf} tells @code{inetd} which ports to listen to
2403 and what server programs to run for them.  Normally each entry in the
2404 file is one line, but you can split it onto multiple lines provided
2405 all but the first line of the entry start with whitespace.  Lines that
2406 start with @samp{#} are comments.
2408 Here are two standard entries in @file{/etc/inetd.conf}:
2410 @smallexample
2411 ftp     stream  tcp     nowait  root    /libexec/ftpd   ftpd
2412 talk    dgram   udp     wait    root    /libexec/talkd  talkd
2413 @end smallexample
2415 An entry has this format:
2417 @smallexample
2418 @var{service} @var{style} @var{protocol} @var{wait} @var{username} @var{program} @var{arguments}
2419 @end smallexample
2421 The @var{service} field says which service this program provides.  It
2422 should be the name of a service defined in @file{/etc/services}.
2423 @code{inetd} uses @var{service} to decide which port to listen on for
2424 this entry.
2426 The fields @var{style} and @var{protocol} specify the communication
2427 style and the protocol to use for the listening socket.  The style
2428 should be the name of a communication style, converted to lower case
2429 and with @samp{SOCK_} deleted---for example, @samp{stream} or
2430 @samp{dgram}.  @var{protocol} should be one of the protocols listed in
2431 @file{/etc/protocols}.  The typical protocol names are @samp{tcp} for
2432 byte stream connections and @samp{udp} for unreliable datagrams.
2434 The @var{wait} field should be either @samp{wait} or @samp{nowait}.
2435 Use @samp{wait} if @var{style} is a connectionless style and the
2436 server, once started, handles multiple requests, as many as come in.
2437 Use @samp{nowait} if @code{inetd} should start a new process for each message
2438 or request that comes in.  If @var{style} uses connections, then
2439 @var{wait} @strong{must} be @samp{nowait}.
2441 @var{user} is the user name that the server should run as.  @code{inetd} runs
2442 as root, so it can set the user ID of its children arbitrarily.  It's
2443 best to avoid using @samp{root} for @var{user} if you can; but some
2444 servers, such as Telnet and FTP, read a username and password
2445 themselves.  These servers need to be root initially so they can log
2446 in as commanded by the data coming over the network.
2448 @var{program} together with @var{arguments} specifies the command to
2449 run to start the server.  @var{program} should be an absolute file
2450 name specifying the executable file to run.  @var{arguments} consists
2451 of any number of whitespace-separated words, which become the
2452 command-line arguments of @var{program}.  The first word in
2453 @var{arguments} is argument zero, which should by convention be the
2454 program name itself (sans directories).
2456 If you edit @file{/etc/inetd.conf}, you can tell @code{inetd} to reread the
2457 file and obey its new contents by sending the @code{inetd} process the
2458 @code{SIGHUP} signal.  You'll have to use @code{ps} to determine the
2459 process ID of the @code{inetd} process, as it is not fixed.
2461 @c !!! could document /etc/inetd.sec
2463 @node Socket Options
2464 @section Socket Options
2465 @cindex socket options
2467 This section describes how to read or set various options that modify
2468 the behavior of sockets and their underlying communications protocols.
2470 @cindex level, for socket options
2471 @cindex socket option level
2472 When you are manipulating a socket option, you must specify which
2473 @dfn{level} the option pertains to.  This describes whether the option
2474 applies to the socket interface, or to a lower-level communications
2475 protocol interface.
2477 @menu
2478 * Socket Option Functions::     The basic functions for setting and getting
2479                                  socket options.
2480 * Socket-Level Options::        Details of the options at the socket level.
2481 @end menu
2483 @node Socket Option Functions
2484 @subsection Socket Option Functions
2486 @pindex sys/socket.h
2487 Here are the functions for examining and modifying socket options.
2488 They are declared in @file{sys/socket.h}.
2490 @comment sys/socket.h
2491 @comment BSD
2492 @deftypefun int getsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, size_t *@var{optlen-ptr})
2493 The @code{getsockopt} function gets information about the value of
2494 option @var{optname} at level @var{level} for socket @var{socket}.
2496 The option value is stored in a buffer that @var{optval} points to.
2497 Before the call, you should supply in @code{*@var{optlen-ptr}} the
2498 size of this buffer; on return, it contains the number of bytes of
2499 information actually stored in the buffer.
2501 Most options interpret the @var{optval} buffer as a single @code{int}
2502 value.
2504 The actual return value of @code{getsockopt} is @code{0} on success
2505 and @code{-1} on failure.  The following @code{errno} error conditions
2506 are defined:
2508 @table @code
2509 @item EBADF
2510 The @var{socket} argument is not a valid file descriptor.
2512 @item ENOTSOCK
2513 The descriptor @var{socket} is not a socket.
2515 @item ENOPROTOOPT
2516 The @var{optname} doesn't make sense for the given @var{level}.
2517 @end table
2518 @end deftypefun
2520 @comment sys/socket.h
2521 @comment BSD
2522 @deftypefun int setsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, size_t @var{optlen})
2523 This function is used to set the socket option @var{optname} at level
2524 @var{level} for socket @var{socket}.  The value of the option is passed
2525 in the buffer @var{optval}, which has size @var{optlen}.
2527 The return value and error codes for @code{setsockopt} are the same as
2528 for @code{getsockopt}.
2529 @end deftypefun
2531 @node Socket-Level Options
2532 @subsection Socket-Level Options
2534 @comment sys/socket.h
2535 @comment BSD
2536 @deftypevr Constant int SOL_SOCKET
2537 Use this constant as the @var{level} argument to @code{getsockopt} or
2538 @code{setsockopt} to manipulate the socket-level options described in
2539 this section.
2540 @end deftypevr
2542 @pindex sys/socket.h
2543 Here is a table of socket-level option names; all are defined in the
2544 header file @file{sys/socket.h}.
2546 @table @code
2547 @comment sys/socket.h
2548 @comment BSD
2549 @item SO_DEBUG
2550 @c Extra blank line here makes the table look better.
2552 This option toggles recording of debugging information in the underlying
2553 protocol modules.  The value has type @code{int}; a nonzero value means
2554 ``yes''.
2555 @c !!! should say how this is used
2556 @c Ok, anyone who knows, please explain.
2558 @comment sys/socket.h
2559 @comment BSD
2560 @item SO_REUSEADDR
2561 This option controls whether @code{bind} (@pxref{Setting Address})
2562 should permit reuse of local addresses for this socket.  If you enable
2563 this option, you can actually have two sockets with the same Internet
2564 port number; but the system won't allow you to use the two
2565 identically-named sockets in a way that would confuse the Internet.  The
2566 reason for this option is that some higher-level Internet protocols,
2567 including FTP, require you to keep reusing the same socket number.
2569 The value has type @code{int}; a nonzero value means ``yes''.
2571 @comment sys/socket.h
2572 @comment BSD
2573 @item SO_KEEPALIVE
2574 This option controls whether the underlying protocol should
2575 periodically transmit messages on a connected socket.  If the peer
2576 fails to respond to these messages, the connection is considered
2577 broken.  The value has type @code{int}; a nonzero value means
2578 ``yes''.
2580 @comment sys/socket.h
2581 @comment BSD
2582 @item SO_DONTROUTE
2583 This option controls whether outgoing messages bypass the normal
2584 message routing facilities.  If set, messages are sent directly to the
2585 network interface instead.  The value has type @code{int}; a nonzero
2586 value means ``yes''.
2588 @comment sys/socket.h
2589 @comment BSD
2590 @item SO_LINGER
2591 This option specifies what should happen when the socket of a type
2592 that promises reliable delivery still has untransmitted messages when
2593 it is closed; see @ref{Closing a Socket}.  The value has type
2594 @code{struct linger}.
2596 @comment sys/socket.h
2597 @comment BSD
2598 @deftp {Data Type} {struct linger}
2599 This structure type has the following members:
2601 @table @code
2602 @item int l_onoff
2603 This field is interpreted as a boolean.  If nonzero, @code{close}
2604 blocks until the data is transmitted or the timeout period has expired.
2606 @item int l_linger
2607 This specifies the timeout period, in seconds.
2608 @end table
2609 @end deftp
2611 @comment sys/socket.h
2612 @comment BSD
2613 @item SO_BROADCAST
2614 This option controls whether datagrams may be broadcast from the socket.
2615 The value has type @code{int}; a nonzero value means ``yes''.
2617 @comment sys/socket.h
2618 @comment BSD
2619 @item SO_OOBINLINE
2620 If this option is set, out-of-band data received on the socket is
2621 placed in the normal input queue.  This permits it to be read using
2622 @code{read} or @code{recv} without specifying the @code{MSG_OOB}
2623 flag.  @xref{Out-of-Band Data}.  The value has type @code{int}; a
2624 nonzero value means ``yes''.
2626 @comment sys/socket.h
2627 @comment BSD
2628 @item SO_SNDBUF
2629 This option gets or sets the size of the output buffer.  The value is a
2630 @code{size_t}, which is the size in bytes.
2632 @comment sys/socket.h
2633 @comment BSD
2634 @item SO_RCVBUF
2635 This option gets or sets the size of the input buffer.  The value is a
2636 @code{size_t}, which is the size in bytes.
2638 @comment sys/socket.h
2639 @comment GNU
2640 @item SO_STYLE
2641 @comment sys/socket.h
2642 @comment BSD
2643 @itemx SO_TYPE
2644 This option can be used with @code{getsockopt} only.  It is used to
2645 get the socket's communication style.  @code{SO_TYPE} is the
2646 historical name, and @code{SO_STYLE} is the preferred name in GNU.
2647 The value has type @code{int} and its value designates a communication
2648 style; see @ref{Communication Styles}.
2650 @comment sys/socket.h
2651 @comment BSD
2652 @item SO_ERROR
2653 @c Extra blank line here makes the table look better.
2655 This option can be used with @code{getsockopt} only.  It is used to reset
2656 the error status of the socket.  The value is an @code{int}, which represents
2657 the previous error status.
2658 @c !!! what is "socket error status"?  this is never defined.
2659 @end table
2661 @node Networks Database
2662 @section Networks Database
2663 @cindex networks database
2664 @cindex converting network number to network name
2665 @cindex converting network name to network number
2667 @pindex /etc/networks
2668 @pindex netdb.h
2669 Many systems come with a database that records a list of networks known
2670 to the system developer.  This is usually kept either in the file
2671 @file{/etc/networks} or in an equivalent from a name server.  This data
2672 base is useful for routing programs such as @code{route}, but it is not
2673 useful for programs that simply communicate over the network.  We
2674 provide functions to access this data base, which are declared in
2675 @file{netdb.h}.
2677 @comment netdb.h
2678 @comment BSD
2679 @deftp {Data Type} {struct netent}
2680 This data type is used to represent information about entries in the
2681 networks database.  It has the following members:
2683 @table @code
2684 @item char *n_name
2685 This is the ``official'' name of the network.
2687 @item char **n_aliases
2688 These are alternative names for the network, represented as a vector
2689 of strings.  A null pointer terminates the array.
2691 @item int n_addrtype
2692 This is the type of the network number; this is always equal to
2693 @code{AF_INET} for Internet networks.
2695 @item unsigned long int n_net
2696 This is the network number.  Network numbers are returned in host
2697 byte order; see @ref{Byte Order}.
2698 @end table
2699 @end deftp
2701 Use the @code{getnetbyname} or @code{getnetbyaddr} functions to search
2702 the networks database for information about a specific network.  The
2703 information is returned in a statically-allocated structure; you must
2704 copy the information if you need to save it.
2706 @comment netdb.h
2707 @comment BSD
2708 @deftypefun {struct netent *} getnetbyname (const char *@var{name})
2709 The @code{getnetbyname} function returns information about the network
2710 named @var{name}.  It returns a null pointer if there is no such
2711 network.
2712 @end deftypefun
2714 @comment netdb.h
2715 @comment BSD
2716 @deftypefun {struct netent *} getnetbyaddr (long @var{net}, int @var{type})
2717 The @code{getnetbyaddr} function returns information about the network
2718 of type @var{type} with number @var{net}.  You should specify a value of
2719 @code{AF_INET} for the @var{type} argument for Internet networks.
2721 @code{getnetbyaddr} returns a null pointer if there is no such
2722 network.
2723 @end deftypefun
2725 You can also scan the networks database using @code{setnetent},
2726 @code{getnetent}, and @code{endnetent}.  Be careful in using these
2727 functions, because they are not reentrant.
2729 @comment netdb.h
2730 @comment BSD
2731 @deftypefun void setnetent (int @var{stayopen})
2732 This function opens and rewinds the networks database.
2734 If the @var{stayopen} argument is nonzero, this sets a flag so that
2735 subsequent calls to @code{getnetbyname} or @code{getnetbyaddr} will
2736 not close the database (as they usually would).  This makes for more
2737 efficiency if you call those functions several times, by avoiding
2738 reopening the database for each call.
2739 @end deftypefun
2741 @comment netdb.h
2742 @comment BSD
2743 @deftypefun {struct netent *} getnetent (void)
2744 This function returns the next entry in the networks database.  It
2745 returns a null pointer if there are no more entries.
2746 @end deftypefun
2748 @comment netdb.h
2749 @comment BSD
2750 @deftypefun void endnetent (void)
2751 This function closes the networks database.
2752 @end deftypefun