Update.
[platform/upstream/glibc.git] / manual / socket.texi
1 @node Sockets, Low-Level Terminal Interface, Pipes and FIFOs, Top
2 @c %MENU% A more complicated IPC mechanism, with networking support
3 @chapter Sockets
4
5 This chapter describes the GNU facilities for interprocess
6 communication using sockets.
7
8 @cindex socket
9 @cindex interprocess communication, with sockets
10 A @dfn{socket} is a generalized interprocess communication channel.
11 Like a pipe, a socket is represented as a file descriptor.  Unlike pipes
12 sockets support communication between unrelated processes, and even
13 between processes running on different machines that communicate over a
14 network.  Sockets are the primary means of communicating with other
15 machines; @code{telnet}, @code{rlogin}, @code{ftp}, @code{talk} and the
16 other familiar network programs use sockets.
17
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.
22
23 @strong{Incomplete:} We do not currently document the facilities for
24 broadcast messages or for configuring Internet interfaces.  The
25 reentrant functions and some newer functions that are related to IPv6
26 aren't documented either so far.
27
28 @menu
29 * Socket Concepts::     Basic concepts you need to know about.
30 * Communication Styles::Stream communication, datagrams and other styles.
31 * Socket Addresses::    How socket names (``addresses'') work.
32 * Interface Naming::    Identifying specific network interfaces.
33 * Local Namespace::     Details about the local namespace.
34 * Internet Namespace::  Details about the Internet namespace.
35 * Misc Namespaces::     Other namespaces not documented fully here.
36 * Open/Close Sockets::  Creating sockets and destroying them.
37 * Connections::         Operations on sockets with connection state.
38 * Datagrams::           Operations on datagram sockets.
39 * Inetd::               Inetd is a daemon that starts servers on request.
40                            The most convenient way to write a server
41                            is to make it work with Inetd.
42 * Socket Options::      Miscellaneous low-level socket options.
43 * Networks Database::   Accessing the database of network names.
44 @end menu
45
46 @node Socket Concepts
47 @section Socket Concepts
48
49 @cindex communication style (of a socket)
50 @cindex style of communication (of a socket)
51 When you create a socket, you must specify the style of communication
52 you want to use and the type of protocol that should implement it.
53 The @dfn{communication style} of a socket defines the user-level
54 semantics of sending and receiving data on the socket.  Choosing a
55 communication style specifies the answers to questions such as these:
56
57 @itemize @bullet
58 @item
59 @cindex packet
60 @cindex byte stream
61 @cindex stream (sockets)
62 @strong{What are the units of data transmission?}  Some communication
63 styles regard the data as a sequence of bytes with no larger
64 structure; others group the bytes into records (which are known in
65 this context as @dfn{packets}).
66
67 @item
68 @cindex loss of data on sockets
69 @cindex data loss on sockets
70 @strong{Can data be lost during normal operation?}  Some communication
71 styles guarantee that all the data sent arrives in the order it was
72 sent (barring system or network crashes); other styles occasionally
73 lose data as a normal part of operation, and may sometimes deliver
74 packets more than once or in the wrong order.
75
76 Designing a program to use unreliable communication styles usually
77 involves taking precautions to detect lost or misordered packets and
78 to retransmit data as needed.
79
80 @item
81 @strong{Is communication entirely with one partner?}  Some
82 communication styles are like a telephone call---you make a
83 @dfn{connection} with one remote socket and then exchange data
84 freely.  Other styles are like mailing letters---you specify a
85 destination address for each message you send.
86 @end itemize
87
88 @cindex namespace (of socket)
89 @cindex domain (of socket)
90 @cindex socket namespace
91 @cindex socket domain
92 You must also choose a @dfn{namespace} for naming the socket.  A socket
93 name (``address'') is meaningful only in the context of a particular
94 namespace.  In fact, even the data type to use for a socket name may
95 depend on the namespace.  Namespaces are also called ``domains'', but we
96 avoid that word as it can be confused with other usage of the same
97 term.  Each namespace has a symbolic name that starts with @samp{PF_}.
98 A corresponding symbolic name starting with @samp{AF_} designates the
99 address format for that namespace.
100
101 @cindex network protocol
102 @cindex protocol (of socket)
103 @cindex socket protocol
104 @cindex protocol family
105 Finally you must choose the @dfn{protocol} to carry out the
106 communication.  The protocol determines what low-level mechanism is used
107 to transmit and receive data.  Each protocol is valid for a particular
108 namespace and communication style; a namespace is sometimes called a
109 @dfn{protocol family} because of this, which is why the namespace names
110 start with @samp{PF_}.
111
112 The rules of a protocol apply to the data passing between two programs,
113 perhaps on different computers; most of these rules are handled by the
114 operating system and you need not know about them.  What you do need to
115 know about protocols is this:
116
117 @itemize @bullet
118 @item
119 In order to have communication between two sockets, they must specify
120 the @emph{same} protocol.
121
122 @item
123 Each protocol is meaningful with particular style/namespace
124 combinations and cannot be used with inappropriate combinations.  For
125 example, the TCP protocol fits only the byte stream style of
126 communication and the Internet namespace.
127
128 @item
129 For each combination of style and namespace there is a @dfn{default
130 protocol}, which you can request by specifying 0 as the protocol
131 number.  And that's what you should normally do---use the default.
132 @end itemize
133
134 Throughout the following description at various places
135 variables/parameters to denote sizes are required.  And here the trouble
136 starts.  In the first implementations the type of these variables was
137 simply @code{int}.  On most machines at that time an @code{int} was 32
138 bits wide, which created a @emph{de facto} standard requiring 32-bit
139 variables.  This is important since references to variables of this type
140 are passed to the kernel.
141
142 Then the POSIX people came and unified the interface with the words "all
143 size values are of type @code{size_t}".  On 64-bit machines
144 @code{size_t} is 64 bits wide, so pointers to variables were no longer
145 possible.
146
147 The Unix98 specification provides a solution by introducing a type
148 @code{socklen_t}.  This type is used in all of the cases that POSIX
149 changed to use @code{size_t}.  The only requirement of this type is that
150 it be an unsigned type of at least 32 bits.  Therefore, implementations
151 which require that references to 32-bit variables be passed can be as
152 happy as implementations which use 64-bit values.
153
154
155 @node Communication Styles
156 @section Communication Styles
157
158 The GNU library includes support for several different kinds of sockets,
159 each with different characteristics.  This section describes the
160 supported socket types.  The symbolic constants listed here are
161 defined in @file{sys/socket.h}.
162 @pindex sys/socket.h
163
164 @comment sys/socket.h
165 @comment BSD
166 @deftypevr Macro int SOCK_STREAM
167 The @code{SOCK_STREAM} style is like a pipe (@pxref{Pipes and FIFOs}).
168 It operates over a connection with a particular remote socket and
169 transmits data reliably as a stream of bytes.
170
171 Use of this style is covered in detail in @ref{Connections}.
172 @end deftypevr
173
174 @comment sys/socket.h
175 @comment BSD
176 @deftypevr Macro int SOCK_DGRAM
177 The @code{SOCK_DGRAM} style is used for sending
178 individually-addressed packets unreliably.
179 It is the diametrical opposite of @code{SOCK_STREAM}.
180
181 Each time you write data to a socket of this kind, that data becomes
182 one packet.  Since @code{SOCK_DGRAM} sockets do not have connections,
183 you must specify the recipient address with each packet.
184
185 The only guarantee that the system makes about your requests to
186 transmit data is that it will try its best to deliver each packet you
187 send.  It may succeed with the sixth packet after failing with the
188 fourth and fifth packets; the seventh packet may arrive before the
189 sixth, and may arrive a second time after the sixth.
190
191 The typical use for @code{SOCK_DGRAM} is in situations where it is
192 acceptable to simply re-send a packet if no response is seen in a
193 reasonable amount of time.
194
195 @xref{Datagrams}, for detailed information about how to use datagram
196 sockets.
197 @end deftypevr
198
199 @ignore
200 @c This appears to be only for the NS domain, which we aren't
201 @c discussing and probably won't support either.
202 @comment sys/socket.h
203 @comment BSD
204 @deftypevr Macro int SOCK_SEQPACKET
205 This style is like @code{SOCK_STREAM} except that the data are
206 structured into packets.
207
208 A program that receives data over a @code{SOCK_SEQPACKET} socket
209 should be prepared to read the entire message packet in a single call
210 to @code{read}; if it only reads part of the message, the remainder of
211 the message is simply discarded instead of being available for
212 subsequent calls to @code{read}.
213
214 Many protocols do not support this communication style.
215 @end deftypevr
216 @end ignore
217
218 @ignore
219 @comment sys/socket.h
220 @comment BSD
221 @deftypevr Macro int SOCK_RDM
222 This style is a reliable version of @code{SOCK_DGRAM}: it sends
223 individually addressed packets, but guarantees that each packet sent
224 arrives exactly once.
225
226 @strong{Warning:} It is not clear this is actually supported
227 by any operating system.
228 @end deftypevr
229 @end ignore
230
231 @comment sys/socket.h
232 @comment BSD
233 @deftypevr Macro int SOCK_RAW
234 This style provides access to low-level network protocols and
235 interfaces.  Ordinary user programs usually have no need to use this
236 style.
237 @end deftypevr
238
239 @node Socket Addresses
240 @section Socket Addresses
241
242 @cindex address of socket
243 @cindex name of socket
244 @cindex binding a socket address
245 @cindex socket address (name) binding
246 The name of a socket is normally called an @dfn{address}.  The
247 functions and symbols for dealing with socket addresses were named
248 inconsistently, sometimes using the term ``name'' and sometimes using
249 ``address''.  You can regard these terms as synonymous where sockets
250 are concerned.
251
252 A socket newly created with the @code{socket} function has no
253 address.  Other processes can find it for communication only if you
254 give it an address.  We call this @dfn{binding} the address to the
255 socket, and the way to do it is with the @code{bind} function.
256
257 You need be concerned with the address of a socket if other processes
258 are to find it and start communicating with it.  You can specify an
259 address for other sockets, but this is usually pointless; the first time
260 you send data from a socket, or use it to initiate a connection, the
261 system assigns an address automatically if you have not specified one.
262
263 Occasionally a client needs to specify an address because the server
264 discriminates based on address; for example, the rsh and rlogin
265 protocols look at the client's socket address and only bypass password
266 checking if it is less than @code{IPPORT_RESERVED} (@pxref{Ports}).
267
268 The details of socket addresses vary depending on what namespace you are
269 using.  @xref{Local Namespace}, or @ref{Internet Namespace}, for specific
270 information.
271
272 Regardless of the namespace, you use the same functions @code{bind} and
273 @code{getsockname} to set and examine a socket's address.  These
274 functions use a phony data type, @code{struct sockaddr *}, to accept the
275 address.  In practice, the address lives in a structure of some other
276 data type appropriate to the address format you are using, but you cast
277 its address to @code{struct sockaddr *} when you pass it to
278 @code{bind}.
279
280 @menu
281 * Address Formats::             About @code{struct sockaddr}.
282 * Setting Address::             Binding an address to a socket.
283 * Reading Address::             Reading the address of a socket.
284 @end menu
285
286 @node Address Formats
287 @subsection Address Formats
288
289 The functions @code{bind} and @code{getsockname} use the generic data
290 type @code{struct sockaddr *} to represent a pointer to a socket
291 address.  You can't use this data type effectively to interpret an
292 address or construct one; for that, you must use the proper data type
293 for the socket's namespace.
294
295 Thus, the usual practice is to construct an address of the proper
296 namespace-specific type, then cast a pointer to @code{struct sockaddr *}
297 when you call @code{bind} or @code{getsockname}.
298
299 The one piece of information that you can get from the @code{struct
300 sockaddr} data type is the @dfn{address format designator}.  This tells
301 you which data type to use to understand the address fully.
302
303 @pindex sys/socket.h
304 The symbols in this section are defined in the header file
305 @file{sys/socket.h}.
306
307 @comment sys/socket.h
308 @comment BSD
309 @deftp {Data Type} {struct sockaddr}
310 The @code{struct sockaddr} type itself has the following members:
311
312 @table @code
313 @item short int sa_family
314 This is the code for the address format of this address.  It
315 identifies the format of the data which follows.
316
317 @item char sa_data[14]
318 This is the actual socket address data, which is format-dependent.  Its
319 length also depends on the format, and may well be more than 14.  The
320 length 14 of @code{sa_data} is essentially arbitrary.
321 @end table
322 @end deftp
323
324 Each address format has a symbolic name which starts with @samp{AF_}.
325 Each of them corresponds to a @samp{PF_} symbol which designates the
326 corresponding namespace.  Here is a list of address format names:
327
328 @table @code
329 @comment sys/socket.h
330 @comment POSIX
331 @item AF_LOCAL
332 @vindex AF_LOCAL
333 This designates the address format that goes with the local namespace.
334 (@code{PF_LOCAL} is the name of that namespace.)  @xref{Local Namespace
335 Details}, for information about this address format.
336
337 @comment sys/socket.h
338 @comment BSD
339 @item AF_UNIX
340 @vindex AF_UNIX
341 This is a synonym for @code{AF_LOCAL}, for compatibility.
342 (@code{PF_UNIX} is likewise a synonym for @code{PF_LOCAL}.)
343
344 @comment sys/socket.h
345 @comment GNU
346 @item AF_FILE
347 @vindex AF_FILE
348 This is another synonym for @code{AF_LOCAL}, for compatibility.
349 (@code{PF_FILE} is likewise a synonym for @code{PF_LOCAL}.)
350
351 @comment sys/socket.h
352 @comment BSD
353 @item AF_INET
354 @vindex AF_INET
355 This designates the address format that goes with the Internet
356 namespace.  (@code{PF_INET} is the name of that namespace.)
357 @xref{Internet Address Formats}.
358
359 @comment sys/socket.h
360 @comment IPv6 Basic API
361 @item AF_INET6
362 This is similar to @code{AF_INET}, but refers to the IPv6 protocol.
363 (@code{PF_INET6} is the name of the corresponding namespace.)
364
365 @comment sys/socket.h
366 @comment BSD
367 @item AF_UNSPEC
368 @vindex AF_UNSPEC
369 This designates no particular address format.  It is used only in rare
370 cases, such as to clear out the default destination address of a
371 ``connected'' datagram socket.  @xref{Sending Datagrams}.
372
373 The corresponding namespace designator symbol @code{PF_UNSPEC} exists
374 for completeness, but there is no reason to use it in a program.
375 @end table
376
377 @file{sys/socket.h} defines symbols starting with @samp{AF_} for many
378 different kinds of networks, most or all of which are not actually
379 implemented.  We will document those that really work as we receive
380 information about how to use them.
381
382 @node Setting Address
383 @subsection Setting the Address of a Socket
384
385 @pindex sys/socket.h
386 Use the @code{bind} function to assign an address to a socket.  The
387 prototype for @code{bind} is in the header file @file{sys/socket.h}.
388 For examples of use, see @ref{Local Socket Example}, or see @ref{Inet Example}.
389
390 @comment sys/socket.h
391 @comment BSD
392 @deftypefun int bind (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
393 The @code{bind} function assigns an address to the socket
394 @var{socket}.  The @var{addr} and @var{length} arguments specify the
395 address; the detailed format of the address depends on the namespace.
396 The first part of the address is always the format designator, which
397 specifies a namespace, and says that the address is in the format of
398 that namespace.
399
400 The return value is @code{0} on success and @code{-1} on failure.  The
401 following @code{errno} error conditions are defined for this function:
402
403 @table @code
404 @item EBADF
405 The @var{socket} argument is not a valid file descriptor.
406
407 @item ENOTSOCK
408 The descriptor @var{socket} is not a socket.
409
410 @item EADDRNOTAVAIL
411 The specified address is not available on this machine.
412
413 @item EADDRINUSE
414 Some other socket is already using the specified address.
415
416 @item EINVAL
417 The socket @var{socket} already has an address.
418
419 @item EACCES
420 You do not have permission to access the requested address.  (In the
421 Internet domain, only the super-user is allowed to specify a port number
422 in the range 0 through @code{IPPORT_RESERVED} minus one; see
423 @ref{Ports}.)
424 @end table
425
426 Additional conditions may be possible depending on the particular namespace
427 of the socket.
428 @end deftypefun
429
430 @node Reading Address
431 @subsection Reading the Address of a Socket
432
433 @pindex sys/socket.h
434 Use the function @code{getsockname} to examine the address of an
435 Internet socket.  The prototype for this function is in the header file
436 @file{sys/socket.h}.
437
438 @comment sys/socket.h
439 @comment BSD
440 @deftypefun int getsockname (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
441 The @code{getsockname} function returns information about the
442 address of the socket @var{socket} in the locations specified by the
443 @var{addr} and @var{length-ptr} arguments.  Note that the
444 @var{length-ptr} is a pointer; you should initialize it to be the
445 allocation size of @var{addr}, and on return it contains the actual
446 size of the address data.
447
448 The format of the address data depends on the socket namespace.  The
449 length of the information is usually fixed for a given namespace, so
450 normally you can know exactly how much space is needed and can provide
451 that much.  The usual practice is to allocate a place for the value
452 using the proper data type for the socket's namespace, then cast its
453 address to @code{struct sockaddr *} to pass it to @code{getsockname}.
454
455 The return value is @code{0} on success and @code{-1} on error.  The
456 following @code{errno} error conditions are defined for this function:
457
458 @table @code
459 @item EBADF
460 The @var{socket} argument is not a valid file descriptor.
461
462 @item ENOTSOCK
463 The descriptor @var{socket} is not a socket.
464
465 @item ENOBUFS
466 There are not enough internal buffers available for the operation.
467 @end table
468 @end deftypefun
469
470 You can't read the address of a socket in the file namespace.  This is
471 consistent with the rest of the system; in general, there's no way to
472 find a file's name from a descriptor for that file.
473
474 @node Interface Naming
475 @section Interface Naming
476
477 Each network interface has a name.  This usually consists of a few
478 letters that relate to the type of interface, which may be followed by a
479 number if there is more than one interface of that type.  Examples
480 might be @code{lo} (the loopback interface) and @code{eth0} (the first
481 Ethernet interface).
482
483 Although such names are convenient for humans, it would be clumsy to
484 have to use them whenever a program needs to refer to an interface.  In
485 such situations an interface is referred to by its @dfn{index}, which is
486 an arbitrarily-assigned small positive integer.
487
488 The following functions, constants and data types are declared in the
489 header file @file{net/if.h}.
490
491 @comment net/if.h
492 @deftypevr Constant size_t IFNAMSIZ
493 This constant defines the maximum buffer size needed to hold an
494 interface name, including its terminating zero byte.
495 @end deftypevr
496
497 @comment net/if.h
498 @comment IPv6 basic API
499 @deftypefun {unsigned int} if_nametoindex (const char *ifname)
500 This function yields the interface index corresponding to a particular
501 name.  If no interface exists with the name given, it returns 0.
502 @end deftypefun
503
504 @comment net/if.h
505 @comment IPv6 basic API
506 @deftypefun {char *} if_indextoname (unsigned int ifindex, char *ifname)
507 This function maps an interface index to its corresponding name.  The
508 returned name is placed in the buffer pointed to by @code{ifname}, which
509 must be at least @code{IFNAMSIZE} bytes in length.  If the index was
510 invalid, the function's return value is a null pointer, otherwise it is
511 @code{ifname}.
512 @end deftypefun
513
514 @comment net/if.h
515 @comment IPv6 basic API
516 @deftp {Data Type} {struct if_nameindex}
517 This data type is used to hold the information about a single
518 interface.  It has the following members:
519
520 @table @code
521 @item unsigned int if_index;
522 This is the interface index.
523
524 @item char *if_name
525 This is the null-terminated index name.
526
527 @end table
528 @end deftp
529
530 @comment net/if.h
531 @comment IPv6 basic API
532 @deftypefun {struct if_nameindex *} if_nameindex (void)
533 This function returns an array of @code{if_nameindex} structures, one
534 for every interface that is present.  The end of the list is indicated
535 by a structure with an interface of 0 and a null name pointer.  If an
536 error occurs, this function returns a null pointer.
537
538 The returned structure must be freed with @code{if_freenameindex} after
539 use.
540 @end deftypefun
541
542 @comment net/if.h
543 @comment IPv6 basic API
544 @deftypefun void if_freenameindex (struct if_nameindex *ptr)
545 This function frees the structure returned by an earlier call to
546 @code{if_nameindex}.
547 @end deftypefun
548
549 @node Local Namespace
550 @section The Local Namespace
551 @cindex local namespace, for sockets
552
553 This section describes the details of the local namespace, whose
554 symbolic name (required when you create a socket) is @code{PF_LOCAL}.
555 The local namespace is also known as ``Unix domain sockets''.  Another
556 name is file namespace since socket addresses are normally implemented
557 as file names.
558
559 @menu
560 * Concepts: Local Namespace Concepts. What you need to understand.
561 * Details: Local Namespace Details.   Address format, symbolic names, etc.
562 * Example: Local Socket Example.      Example of creating a socket.
563 @end menu
564
565 @node Local Namespace Concepts
566 @subsection Local Namespace Concepts
567
568 In the local namespace socket addresses are file names.  You can specify
569 any file name you want as the address of the socket, but you must have
570 write permission on the directory containing it.  In order to connect to
571 a socket you must have read permission for it.  It's common to put
572 these files in the @file{/tmp} directory.
573
574 One peculiarity of the local namespace is that the name is only used
575 when opening the connection; once open the address is not meaningful and
576 may not exist.
577
578 Another peculiarity is that you cannot connect to such a socket from
579 another machine--not even if the other machine shares the file system
580 which contains the name of the socket.  You can see the socket in a
581 directory listing, but connecting to it never succeeds.  Some programs
582 take advantage of this, such as by asking the client to send its own
583 process ID, and using the process IDs to distinguish between clients.
584 However, we recommend you not use this method in protocols you design,
585 as we might someday permit connections from other machines that mount
586 the same file systems.  Instead, send each new client an identifying
587 number if you want it to have one.
588
589 After you close a socket in the local namespace, you should delete the
590 file name from the file system.  Use @code{unlink} or @code{remove} to
591 do this; see @ref{Deleting Files}.
592
593 The local namespace supports just one protocol for any communication
594 style; it is protocol number @code{0}.
595
596 @node Local Namespace Details
597 @subsection Details of Local Namespace
598
599 @pindex sys/socket.h
600 To create a socket in the local namespace, use the constant
601 @code{PF_LOCAL} as the @var{namespace} argument to @code{socket} or
602 @code{socketpair}.  This constant is defined in @file{sys/socket.h}.
603
604 @comment sys/socket.h
605 @comment POSIX
606 @deftypevr Macro int PF_LOCAL
607 This designates the local namespace, in which socket addresses are local
608 names, and its associated family of protocols.  @code{PF_Local} is the
609 macro used by Posix.1g.
610 @end deftypevr
611
612 @comment sys/socket.h
613 @comment BSD
614 @deftypevr Macro int PF_UNIX
615 This is a synonym for @code{PF_LOCAL}, for compatibility's sake.
616 @end deftypevr
617
618 @comment sys/socket.h
619 @comment GNU
620 @deftypevr Macro int PF_FILE
621 This is a synonym for @code{PF_LOCAL}, for compatibility's sake.
622 @end deftypevr
623
624 The structure for specifying socket names in the local namespace is
625 defined in the header file @file{sys/un.h}:
626 @pindex sys/un.h
627
628 @comment sys/un.h
629 @comment BSD
630 @deftp {Data Type} {struct sockaddr_un}
631 This structure is used to specify local namespace socket addresses.  It has
632 the following members:
633
634 @table @code
635 @item short int sun_family
636 This identifies the address family or format of the socket address.
637 You should store the value @code{AF_LOCAL} to designate the local
638 namespace.  @xref{Socket Addresses}.
639
640 @item char sun_path[108]
641 This is the file name to use.
642
643 @strong{Incomplete:}  Why is 108 a magic number?  RMS suggests making
644 this a zero-length array and tweaking the following example to use
645 @code{alloca} to allocate an appropriate amount of storage based on
646 the length of the filename.
647 @end table
648 @end deftp
649
650 You should compute the @var{length} parameter for a socket address in
651 the local namespace as the sum of the size of the @code{sun_family}
652 component and the string length (@emph{not} the allocation size!) of
653 the file name string.  This can be done using the macro @code{SUN_LEN}:
654
655 @comment sys/un.h
656 @comment BSD
657 @deftypefn {Macro} int SUN_LEN (@emph{struct sockaddr_un *} @var{ptr})
658 The macro computes the length of socket address in the local namespace.
659 @end deftypefn
660
661 @node Local Socket Example
662 @subsection Example of Local-Namespace Sockets
663
664 Here is an example showing how to create and name a socket in the local
665 namespace.
666
667 @smallexample
668 @include mkfsock.c.texi
669 @end smallexample
670
671 @node Internet Namespace
672 @section The Internet Namespace
673 @cindex Internet namespace, for sockets
674
675 This section describes the details of the protocols and socket naming
676 conventions used in the Internet namespace.
677
678 Originally the Internet namespace used only IP version 4 (IPv4).  With
679 the growing number of hosts on the Internet, a new protocol with a
680 larger address space was necessary: IP version 6 (IPv6).  IPv6
681 introduces 128-bit addresses (IPv4 has 32-bit addresses) and other
682 features, and will eventually replace IPv4.
683
684 To create a socket in the IPv4 Internet namespace, use the symbolic name
685 @code{PF_INET} of this namespace as the @var{namespace} argument to
686 @code{socket} or @code{socketpair}.  For IPv6 addresses you need the
687 macro @code{PF_INET6}. These macros are defined in @file{sys/socket.h}.
688 @pindex sys/socket.h
689
690 @comment sys/socket.h
691 @comment BSD
692 @deftypevr Macro int PF_INET
693 This designates the IPv4 Internet namespace and associated family of
694 protocols.
695 @end deftypevr
696
697 @comment sys/socket.h
698 @comment X/Open
699 @deftypevr Macro int PF_INET6
700 This designates the IPv6 Internet namespace and associated family of
701 protocols.
702 @end deftypevr
703
704 A socket address for the Internet namespace includes the following components:
705
706 @itemize @bullet
707 @item
708 The address of the machine you want to connect to.  Internet addresses
709 can be specified in several ways; these are discussed in @ref{Internet
710 Address Formats}, @ref{Host Addresses} and @ref{Host Names}.
711
712 @item
713 A port number for that machine.  @xref{Ports}.
714 @end itemize
715
716 You must ensure that the address and port number are represented in a
717 canonical format called @dfn{network byte order}.  @xref{Byte Order},
718 for information about this.
719
720 @menu
721 * Internet Address Formats::    How socket addresses are specified in the
722                                  Internet namespace.
723 * Host Addresses::              All about host addresses of Internet host.
724 * Protocols Database::          Referring to protocols by name.
725 * Ports::                       Internet port numbers.
726 * Services Database::           Ports may have symbolic names.
727 * Byte Order::                  Different hosts may use different byte
728                                  ordering conventions; you need to
729                                  canonicalize host address and port number.
730 * Inet Example::                Putting it all together.
731 @end menu
732
733 @node Internet Address Formats
734 @subsection Internet Socket Address Formats
735
736 In the Internet namespace, for both IPv4 (@code{AF_INET}) and IPv6
737 (@code{AF_INET6}), a socket address consists of a host address
738 and a port on that host.  In addition, the protocol you choose serves
739 effectively as a part of the address because local port numbers are
740 meaningful only within a particular protocol.
741
742 The data types for representing socket addresses in the Internet namespace
743 are defined in the header file @file{netinet/in.h}.
744 @pindex netinet/in.h
745
746 @comment netinet/in.h
747 @comment BSD
748 @deftp {Data Type} {struct sockaddr_in}
749 This is the data type used to represent socket addresses in the
750 Internet namespace.  It has the following members:
751
752 @table @code
753 @item sa_family_t sin_family
754 This identifies the address family or format of the socket address.
755 You should store the value @code{AF_INET} in this member.
756 @xref{Socket Addresses}.
757
758 @item struct in_addr sin_addr
759 This is the Internet address of the host machine.  @xref{Host
760 Addresses}, and @ref{Host Names}, for how to get a value to store
761 here.
762
763 @item unsigned short int sin_port
764 This is the port number.  @xref{Ports}.
765 @end table
766 @end deftp
767
768 When you call @code{bind} or @code{getsockname}, you should specify
769 @code{sizeof (struct sockaddr_in)} as the @var{length} parameter if
770 you are using an IPv4 Internet namespace socket address.
771
772 @deftp {Data Type} {struct sockaddr_in6}
773 This is the data type used to represent socket addresses in the IPv6
774 namespace.  It has the following members:
775
776 @table @code
777 @item sa_family_t sin6_family
778 This identifies the address family or format of the socket address.
779 You should store the value of @code{AF_INET6} in this member.
780 @xref{Socket Addresses}.
781
782 @item struct in6_addr sin6_addr
783 This is the IPv6 address of the host machine.  @xref{Host
784 Addresses}, and @ref{Host Names}, for how to get a value to store
785 here.
786
787 @item uint32_t sin6_flowinfo
788 This is a currently unimplemented field.
789
790 @item uint16_t sin6_port
791 This is the port number.  @xref{Ports}.
792
793 @end table
794 @end deftp
795
796 @node Host Addresses
797 @subsection Host Addresses
798
799 Each computer on the Internet has one or more @dfn{Internet addresses},
800 numbers which identify that computer among all those on the Internet.
801 Users typically write IPv4 numeric host addresses as sequences of four
802 numbers, separated by periods, as in @samp{128.52.46.32}, and IPv6
803 numeric host addresses as sequences of up to eight numbers separated by
804 colons, as in @samp{5f03:1200:836f:c100::1}.
805
806 Each computer also has one or more @dfn{host names}, which are strings
807 of words separated by periods, as in @samp{mescaline.gnu.org}.
808
809 Programs that let the user specify a host typically accept both numeric
810 addresses and host names.  To open a connection a program needs a
811 numeric address, and so must convert a host name to the numeric address
812 it stands for.
813
814 @menu
815 * Abstract Host Addresses::     What a host number consists of.
816 * Data type: Host Address Data Type.    Data type for a host number.
817 * Functions: Host Address Functions.    Functions to operate on them.
818 * Names: Host Names.            Translating host names to host numbers.
819 @end menu
820
821 @node Abstract Host Addresses
822 @subsubsection Internet Host Addresses
823 @cindex host address, Internet
824 @cindex Internet host address
825
826 @ifinfo
827 Each computer on the Internet has one or more Internet addresses,
828 numbers which identify that computer among all those on the Internet.
829 @end ifinfo
830
831 @cindex network number
832 @cindex local network address number
833 An IPv4 Internet host address is a number containing four bytes of data.
834 Historically these are divided into two parts, a @dfn{network number} and a
835 @dfn{local network address number} within that network.  In the
836 mid-1990s classless addresses were introduced which changed this
837 behaviour.  Since some functions implicitly expect the old definitions,
838 we first describe the class-based network and will then describe
839 classless addresses.  IPv6 uses only classless addresses and therefore
840 the following paragraphs don't apply.
841
842 The class-based IPv4 network number consists of the first one, two or
843 three bytes; the rest of the bytes are the local address.
844
845 IPv4 network numbers are registered with the Network Information Center
846 (NIC), and are divided into three classes---A, B and C.  The local
847 network address numbers of individual machines are registered with the
848 administrator of the particular network.
849
850 Class A networks have single-byte numbers in the range 0 to 127.  There
851 are only a small number of Class A networks, but they can each support a
852 very large number of hosts.  Medium-sized Class B networks have two-byte
853 network numbers, with the first byte in the range 128 to 191.  Class C
854 networks are the smallest; they have three-byte network numbers, with
855 the first byte in the range 192-255.  Thus, the first 1, 2, or 3 bytes
856 of an Internet address specify a network.  The remaining bytes of the
857 Internet address specify the address within that network.
858
859 The Class A network 0 is reserved for broadcast to all networks.  In
860 addition, the host number 0 within each network is reserved for broadcast
861 to all hosts in that network.  These uses are obsolete now but for
862 compatibility reasons you shouldn't use network 0 and host number 0.
863
864 The Class A network 127 is reserved for loopback; you can always use
865 the Internet address @samp{127.0.0.1} to refer to the host machine.
866
867 Since a single machine can be a member of multiple networks, it can
868 have multiple Internet host addresses.  However, there is never
869 supposed to be more than one machine with the same host address.
870
871 @c !!! this section could document the IN_CLASS* macros in <netinet/in.h>.
872 @c No, it shouldn't since they're obsolete.
873
874 @cindex standard dot notation, for Internet addresses
875 @cindex dot notation, for Internet addresses
876 There are four forms of the @dfn{standard numbers-and-dots notation}
877 for Internet addresses:
878
879 @table @code
880 @item @var{a}.@var{b}.@var{c}.@var{d}
881 This specifies all four bytes of the address individually and is the
882 commonly used representation.
883
884 @item @var{a}.@var{b}.@var{c}
885 The last part of the address, @var{c}, is interpreted as a 2-byte quantity.
886 This is useful for specifying host addresses in a Class B network with
887 network address number @code{@var{a}.@var{b}}.
888
889 @item @var{a}.@var{b}
890 The last part of the address, @var{b}, is interpreted as a 3-byte quantity.
891 This is useful for specifying host addresses in a Class A network with
892 network address number @var{a}.
893
894 @item @var{a}
895 If only one part is given, this corresponds directly to the host address
896 number.
897 @end table
898
899 Within each part of the address, the usual C conventions for specifying
900 the radix apply.  In other words, a leading @samp{0x} or @samp{0X} implies
901 hexadecimal radix; a leading @samp{0} implies octal; and otherwise decimal
902 radix is assumed.
903
904 @subsubheading Classless Addresses
905
906 IPv4 addresses (and IPv6 addresses also) are now considered classless;
907 the distinction between classes A, B and C can be ignored.  Instead an
908 IPv4 host address consists of a 32-bit address and a 32-bit mask.  The
909 mask contains set bits for the network part and cleared bits for the
910 host part.  The network part is contiguous from the left, with the
911 remaining bits representing the host.  As a consequence, the netmask can
912 simply be specified as the number of set bits.  Classes A, B and C are
913 just special cases of this general rule.  For example, class A addresses
914 have a netmask of @samp{255.0.0.0} or a prefix length of 8.
915
916 Classless IPv4 network addresses are written in numbers-and-dots
917 notation with the prefix length appended and a slash as separator.  For
918 example the class A network 10 is written as @samp{10.0.0.0/8}.
919
920 @subsubheading IPv6 Addresses
921
922 IPv6 addresses contain 128 bits (IPv4 has 32 bits) of data.  A host
923 address is usually written as eight 16-bit hexadecimal numbers that are
924 separated by colons.  Two colons are used to abbreviate strings of
925 consecutive zeros.  For example, the IPv6 loopback address
926 @samp{0:0:0:0:0:0:0:1} can just be written as @samp{::1}.
927
928 @node Host Address Data Type
929 @subsubsection Host Address Data Type
930
931 IPv4 Internet host addresses are represented in some contexts as integers
932 (type @code{uint32_t}).  In other contexts, the integer is
933 packaged inside a structure of type @code{struct in_addr}.  It would
934 be better if the usage were made consistent, but it is not hard to extract
935 the integer from the structure or put the integer into a structure.
936
937 You will find older code that uses @code{unsigned long int} for
938 IPv4 Internet host addresses instead of @code{uint32_t} or @code{struct
939 in_addr}.  Historically @code{unsigned long int} was a 32-bit number but
940 with 64-bit machines this has changed.  Using @code{unsigned long int}
941 might break the code if it is used on machines where this type doesn't
942 have 32 bits.  @code{uint32_t} is specified by Unix98 and guaranteed to have
943 32 bits.
944
945 IPv6 Internet host addresses have 128 bits and are packaged inside a
946 structure of type @code{struct in6_addr}.
947
948 The following basic definitions for Internet addresses are declared in
949 the header file @file{netinet/in.h}:
950 @pindex netinet/in.h
951
952 @comment netinet/in.h
953 @comment BSD
954 @deftp {Data Type} {struct in_addr}
955 This data type is used in certain contexts to contain an IPv4 Internet
956 host address.  It has just one field, named @code{s_addr}, which records
957 the host address number as an @code{uint32_t}.
958 @end deftp
959
960 @comment netinet/in.h
961 @comment BSD
962 @deftypevr Macro {uint32_t} INADDR_LOOPBACK
963 You can use this constant to stand for ``the address of this machine,''
964 instead of finding its actual address.  It is the IPv4 Internet address
965 @samp{127.0.0.1}, which is usually called @samp{localhost}.  This
966 special constant saves you the trouble of looking up the address of your
967 own machine.  Also, the system usually implements @code{INADDR_LOOPBACK}
968 specially, avoiding any network traffic for the case of one machine
969 talking to itself.
970 @end deftypevr
971
972 @comment netinet/in.h
973 @comment BSD
974 @deftypevr Macro {uint32_t} INADDR_ANY
975 You can use this constant to stand for ``any incoming address'' when
976 binding to an address.  @xref{Setting Address}.  This is the usual
977 address to give in the @code{sin_addr} member of @w{@code{struct
978 sockaddr_in}} when you want to accept Internet connections.
979 @end deftypevr
980
981 @comment netinet/in.h
982 @comment BSD
983 @deftypevr Macro {uint32_t} INADDR_BROADCAST
984 This constant is the address you use to send a broadcast message.
985 @c !!! broadcast needs further documented
986 @end deftypevr
987
988 @comment netinet/in.h
989 @comment BSD
990 @deftypevr Macro {uint32_t} INADDR_NONE
991 This constant is returned by some functions to indicate an error.
992 @end deftypevr
993
994 @comment netinet/in.h
995 @comment IPv6 basic API
996 @deftp {Data Type} {struct in6_addr}
997 This data type is used to store an IPv6 address.  It stores 128 bits of
998 data, which can be accessed (via a union) in a variety of ways.
999 @end deftp
1000
1001 @comment netinet/in.h
1002 @comment IPv6 basic API
1003 @deftypevr Constant {struct in6_addr} in6addr_loopback
1004 This constant is the IPv6 address @samp{::1}, the loopback address.  See
1005 above for a description of what this means.  The macro
1006 @code{IN6ADDR_LOOPBACK_INIT} is provided to allow you to initialize your
1007 own variables to this value.
1008 @end deftypevr
1009
1010 @comment netinet/in.h
1011 @comment IPv6 basic API
1012 @deftypevr Constant {struct in6_addr} in6addr_any
1013 This constant is the IPv6 address @samp{::}, the unspecified address.  See
1014 above for a description of what this means.  The macro
1015 @code{IN6ADDR_ANY_INIT} is provided to allow you to initialize your
1016 own variables to this value.
1017 @end deftypevr
1018
1019 @node Host Address Functions
1020 @subsubsection Host Address Functions
1021
1022 @pindex arpa/inet.h
1023 @noindent
1024 These additional functions for manipulating Internet addresses are
1025 declared in the header file @file{arpa/inet.h}.  They represent Internet
1026 addresses in network byte order, and network numbers and
1027 local-address-within-network numbers in host byte order.  @xref{Byte
1028 Order}, for an explanation of network and host byte order.
1029
1030 @comment arpa/inet.h
1031 @comment BSD
1032 @deftypefun int inet_aton (const char *@var{name}, struct in_addr *@var{addr})
1033 This function converts the IPv4 Internet host address @var{name}
1034 from the standard numbers-and-dots notation into binary data and stores
1035 it in the @code{struct in_addr} that @var{addr} points to.
1036 @code{inet_aton} returns nonzero if the address is valid, zero if not.
1037 @end deftypefun
1038
1039 @comment arpa/inet.h
1040 @comment BSD
1041 @deftypefun {uint32_t} inet_addr (const char *@var{name})
1042 This function converts the IPv4 Internet host address @var{name} from the
1043 standard numbers-and-dots notation into binary data.  If the input is
1044 not valid, @code{inet_addr} returns @code{INADDR_NONE}.  This is an
1045 obsolete interface to @code{inet_aton}, described immediately above. It
1046 is obsolete because @code{INADDR_NONE} is a valid address
1047 (255.255.255.255), and @code{inet_aton} provides a cleaner way to
1048 indicate error return.
1049 @end deftypefun
1050
1051 @comment arpa/inet.h
1052 @comment BSD
1053 @deftypefun {uint32_t} inet_network (const char *@var{name})
1054 This function extracts the network number from the address @var{name},
1055 given in the standard numbers-and-dots notation. The returned address is
1056 in host order. If the input is not valid, @code{inet_network} returns
1057 @code{-1}.
1058
1059 The function works only with traditional IPv4 class A, B and C network
1060 types.  It doesn't work with classless addresses and shouldn't be used
1061 anymore.
1062 @end deftypefun
1063
1064 @comment arpa/inet.h
1065 @comment BSD
1066 @deftypefun {char *} inet_ntoa (struct in_addr @var{addr})
1067 This function converts the IPv4 Internet host address @var{addr} to a
1068 string in the standard numbers-and-dots notation.  The return value is
1069 a pointer into a statically-allocated buffer.  Subsequent calls will
1070 overwrite the same buffer, so you should copy the string if you need
1071 to save it.
1072
1073 In multi-threaded programs each thread has an own statically-allocated
1074 buffer.  But still subsequent calls of @code{inet_ntoa} in the same
1075 thread will overwrite the result of the last call.
1076
1077 Instead of @code{inet_ntoa} the newer function @code{inet_ntop} which is
1078 described below should be used since it handles both IPv4 and IPv6
1079 addresses.
1080 @end deftypefun
1081
1082 @comment arpa/inet.h
1083 @comment BSD
1084 @deftypefun {struct in_addr} inet_makeaddr (uint32_t @var{net}, uint32_t @var{local})
1085 This function makes an IPv4 Internet host address by combining the network
1086 number @var{net} with the local-address-within-network number
1087 @var{local}.
1088 @end deftypefun
1089
1090 @comment arpa/inet.h
1091 @comment BSD
1092 @deftypefun uint32_t inet_lnaof (struct in_addr @var{addr})
1093 This function returns the local-address-within-network part of the
1094 Internet host address @var{addr}.
1095
1096 The function works only with traditional IPv4 class A, B and C network
1097 types.  It doesn't work with classless addresses and shouldn't be used
1098 anymore.
1099 @end deftypefun
1100
1101 @comment arpa/inet.h
1102 @comment BSD
1103 @deftypefun uint32_t inet_netof (struct in_addr @var{addr})
1104 This function returns the network number part of the Internet host
1105 address @var{addr}.
1106
1107 The function works only with traditional IPv4 class A, B and C network
1108 types.  It doesn't work with classless addresses and shouldn't be used
1109 anymore.
1110 @end deftypefun
1111
1112 @comment arpa/inet.h
1113 @comment IPv6 basic API
1114 @deftypefun int inet_pton (int @var{af}, const char *@var{cp}, void *@var{buf})
1115 This function converts an Internet address (either IPv4 or IPv6) from
1116 presentation (textual) to network (binary) format.  @var{af} should be
1117 either @code{AF_INET} or @code{AF_INET6}, as appropriate for the type of
1118 address being converted.  @var{cp} is a pointer to the input string, and
1119 @var{buf} is a pointer to a buffer for the result.  It is the caller's
1120 responsibility to make sure the buffer is large enough.
1121 @end deftypefun
1122
1123 @comment arpa/inet.h
1124 @comment IPv6 basic API
1125 @deftypefun {const char *} inet_ntop (int @var{af}, const void *@var{cp}, char *@var{buf}, size_t @var{len})
1126 This function converts an Internet address (either IPv4 or IPv6) from
1127 network (binary) to presentation (textual) form.  @var{af} should be
1128 either @code{AF_INET} or @code{AF_INET6}, as appropriate.  @var{cp} is a
1129 pointer to the address to be converted.  @var{buf} should be a pointer
1130 to a buffer to hold the result, and @var{len} is the length of this
1131 buffer.  The return value from the function will be this buffer address.
1132 @end deftypefun
1133
1134 @node Host Names
1135 @subsubsection Host Names
1136 @cindex hosts database
1137 @cindex converting host name to address
1138 @cindex converting host address to name
1139
1140 Besides the standard numbers-and-dots notation for Internet addresses,
1141 you can also refer to a host by a symbolic name.  The advantage of a
1142 symbolic name is that it is usually easier to remember.  For example,
1143 the machine with Internet address @samp{158.121.106.19} is also known as
1144 @samp{alpha.gnu.org}; and other machines in the @samp{gnu.org}
1145 domain can refer to it simply as @samp{alpha}.
1146
1147 @pindex /etc/hosts
1148 @pindex netdb.h
1149 Internally, the system uses a database to keep track of the mapping
1150 between host names and host numbers.  This database is usually either
1151 the file @file{/etc/hosts} or an equivalent provided by a name server.
1152 The functions and other symbols for accessing this database are declared
1153 in @file{netdb.h}.  They are BSD features, defined unconditionally if
1154 you include @file{netdb.h}.
1155
1156 @comment netdb.h
1157 @comment BSD
1158 @deftp {Data Type} {struct hostent}
1159 This data type is used to represent an entry in the hosts database.  It
1160 has the following members:
1161
1162 @table @code
1163 @item char *h_name
1164 This is the ``official'' name of the host.
1165
1166 @item char **h_aliases
1167 These are alternative names for the host, represented as a null-terminated
1168 vector of strings.
1169
1170 @item int h_addrtype
1171 This is the host address type; in practice, its value is always either
1172 @code{AF_INET} or @code{AF_INET6}, with the latter being used for IPv6
1173 hosts.  In principle other kinds of addresses could be represented in
1174 the database as well as Internet addresses; if this were done, you
1175 might find a value in this field other than @code{AF_INET} or
1176 @code{AF_INET6}.  @xref{Socket Addresses}.
1177
1178 @item int h_length
1179 This is the length, in bytes, of each address.
1180
1181 @item char **h_addr_list
1182 This is the vector of addresses for the host.  (Recall that the host
1183 might be connected to multiple networks and have different addresses on
1184 each one.)  The vector is terminated by a null pointer.
1185
1186 @item char *h_addr
1187 This is a synonym for @code{h_addr_list[0]}; in other words, it is the
1188 first host address.
1189 @end table
1190 @end deftp
1191
1192 As far as the host database is concerned, each address is just a block
1193 of memory @code{h_length} bytes long.  But in other contexts there is an
1194 implicit assumption that you can convert IPv4 addresses to a
1195 @code{struct in_addr} or an @code{uint32_t}.  Host addresses in
1196 a @code{struct hostent} structure are always given in network byte
1197 order; see @ref{Byte Order}.
1198
1199 You can use @code{gethostbyname}, @code{gethostbyname2} or
1200 @code{gethostbyaddr} to search the hosts database for information about
1201 a particular host.  The information is returned in a
1202 statically-allocated structure; you must copy the information if you
1203 need to save it across calls.  You can also use @code{getaddrinfo} and
1204 @code{getnameinfo} to obtain this information.
1205
1206 @comment netdb.h
1207 @comment BSD
1208 @deftypefun {struct hostent *} gethostbyname (const char *@var{name})
1209 The @code{gethostbyname} function returns information about the host
1210 named @var{name}.  If the lookup fails, it returns a null pointer.
1211 @end deftypefun
1212
1213 @comment netdb.h
1214 @comment IPv6 Basic API
1215 @deftypefun {struct hostent *} gethostbyname2 (const char *@var{name}, int @var{af})
1216 The @code{gethostbyname2} function is like @code{gethostbyname}, but
1217 allows the caller to specify the desired address family (e.g.@:
1218 @code{AF_INET} or @code{AF_INET6}) of the result.
1219 @end deftypefun
1220
1221 @comment netdb.h
1222 @comment BSD
1223 @deftypefun {struct hostent *} gethostbyaddr (const char *@var{addr}, size_t @var{length}, int @var{format})
1224 The @code{gethostbyaddr} function returns information about the host
1225 with Internet address @var{addr}.  The parameter @var{addr} is not
1226 really a pointer to char - it can be a pointer to an IPv4 or an IPv6
1227 address. The @var{length} argument is the size (in bytes) of the address
1228 at @var{addr}.  @var{format} specifies the address format; for an IPv4
1229 Internet address, specify a value of @code{AF_INET}; for an IPv6
1230 Internet address, use @code{AF_INET6}.
1231
1232 If the lookup fails, @code{gethostbyaddr} returns a null pointer.
1233 @end deftypefun
1234
1235 @vindex h_errno
1236 If the name lookup by @code{gethostbyname} or @code{gethostbyaddr}
1237 fails, you can find out the reason by looking at the value of the
1238 variable @code{h_errno}.  (It would be cleaner design for these
1239 functions to set @code{errno}, but use of @code{h_errno} is compatible
1240 with other systems.)
1241
1242 Here are the error codes that you may find in @code{h_errno}:
1243
1244 @table @code
1245 @comment netdb.h
1246 @comment BSD
1247 @item HOST_NOT_FOUND
1248 @vindex HOST_NOT_FOUND
1249 No such host is known in the database.
1250
1251 @comment netdb.h
1252 @comment BSD
1253 @item TRY_AGAIN
1254 @vindex TRY_AGAIN
1255 This condition happens when the name server could not be contacted.  If
1256 you try again later, you may succeed then.
1257
1258 @comment netdb.h
1259 @comment BSD
1260 @item NO_RECOVERY
1261 @vindex NO_RECOVERY
1262 A non-recoverable error occurred.
1263
1264 @comment netdb.h
1265 @comment BSD
1266 @item NO_ADDRESS
1267 @vindex NO_ADDRESS
1268 The host database contains an entry for the name, but it doesn't have an
1269 associated Internet address.
1270 @end table
1271
1272 The lookup functions above all have one in common: they are not
1273 reentrant and therefore unusable in multi-threaded applications.
1274 Therefore provides the GNU C library a new set of functions which can be
1275 used in this context.
1276
1277 @comment netdb.h
1278 @comment GNU
1279 @deftypefun int gethostbyname_r (const char *restrict @var{name}, struct hostent *restrict @var{result_buf}, char *restrict @var{buf}, size_t @var{buflen}, struct hostent **restrict @var{result}, int *restrict @var{h_errnop})
1280 The @code{gethostbyname_r} function returns information about the host
1281 named @var{name}.  The caller must pass a pointer to an object of type
1282 @code{struct hostent} in the @var{result_buf} parameter.  In addition
1283 the function may need extra buffer space and the caller must pass an
1284 pointer and the size of the buffer in the @var{buf} and @var{buflen}
1285 parameters.
1286
1287 A pointer to the buffer, in which the result is stored, is available in
1288 @code{*@var{result}} after the function call successfully returned.  If
1289 an error occurs or if no entry is found, the pointer @code{*@var{result}}
1290 is a null pointer.  Success is signalled by a zero return value.  If the
1291 function failed the return value is an error number.  In addition to the
1292 errors defined for @code{gethostbyname} it can also be @code{ERANGE}.
1293 In this case the call should be repeated with a larger buffer.
1294 Additional error information is not stored in the global variable
1295 @code{h_errno} but instead in the object pointed to by @var{h_errnop}.
1296
1297 Here's a small example:
1298 @smallexample
1299 struct hostent *
1300 gethostname (char *host)
1301 @{
1302   struct hostent hostbuf, *hp;
1303   size_t hstbuflen;
1304   char *tmphstbuf;
1305   int res;
1306   int herr;
1307
1308   hstbuflen = 1024;
1309   tmphstbuf = malloc (hstbuflen);
1310
1311   while ((res = gethostbyname_r (host, &hostbuf, tmphstbuf, hstbuflen,
1312                                  &hp, &herr)) == ERANGE)
1313     @{
1314       /* Enlarge the buffer.  */
1315       hstbuflen *= 2;
1316       tmphstbuf = realloc (tmphstbuf, hstbuflen);
1317     @}
1318   /*  Check for errors.  */
1319   if (res || hp == NULL)
1320     return NULL;
1321   return hp->h_name;
1322 @}
1323 @end smallexample
1324 @end deftypefun
1325
1326 @comment netdb.h
1327 @comment GNU
1328 @deftypefun int gethostbyname2_r (const char *@var{name}, int @var{af}, struct hostent *restrict @var{result_buf}, char *restrict @var{buf}, size_t @var{buflen}, struct hostent **restrict @var{result}, int *restrict @var{h_errnop})
1329 The @code{gethostbyname2_r} function is like @code{gethostbyname_r}, but
1330 allows the caller to specify the desired address family (e.g.@:
1331 @code{AF_INET} or @code{AF_INET6}) for the result.
1332 @end deftypefun
1333
1334 @comment netdb.h
1335 @comment GNU
1336 @deftypefun int gethostbyaddr_r (const char *@var{addr}, size_t @var{length}, int @var{format}, struct hostent *restrict @var{result_buf}, char *restrict @var{buf}, size_t @var{buflen}, struct hostent **restrict @var{result}, int *restrict @var{h_errnop})
1337 The @code{gethostbyaddr_r} function returns information about the host
1338 with Internet address @var{addr}.  The parameter @var{addr} is not
1339 really a pointer to char - it can be a pointer to an IPv4 or an IPv6
1340 address. The @var{length} argument is the size (in bytes) of the address
1341 at @var{addr}.  @var{format} specifies the address format; for an IPv4
1342 Internet address, specify a value of @code{AF_INET}; for an IPv6
1343 Internet address, use @code{AF_INET6}.
1344
1345 Similar to the @code{gethostbyname_r} function, the caller must provide
1346 buffers for the result and memory used internally.  In case of success
1347 the function returns zero.  Otherwise the value is an error number where
1348 @code{ERANGE} has the special meaning that the caller-provided buffer is
1349 too small.
1350 @end deftypefun
1351
1352 You can also scan the entire hosts database one entry at a time using
1353 @code{sethostent}, @code{gethostent} and @code{endhostent}.  Be careful
1354 when using these functions because they are not reentrant.
1355
1356 @comment netdb.h
1357 @comment BSD
1358 @deftypefun void sethostent (int @var{stayopen})
1359 This function opens the hosts database to begin scanning it.  You can
1360 then call @code{gethostent} to read the entries.
1361
1362 @c There was a rumor that this flag has different meaning if using the DNS,
1363 @c but it appears this description is accurate in that case also.
1364 If the @var{stayopen} argument is nonzero, this sets a flag so that
1365 subsequent calls to @code{gethostbyname} or @code{gethostbyaddr} will
1366 not close the database (as they usually would).  This makes for more
1367 efficiency if you call those functions several times, by avoiding
1368 reopening the database for each call.
1369 @end deftypefun
1370
1371 @comment netdb.h
1372 @comment BSD
1373 @deftypefun {struct hostent *} gethostent (void)
1374 This function returns the next entry in the hosts database.  It
1375 returns a null pointer if there are no more entries.
1376 @end deftypefun
1377
1378 @comment netdb.h
1379 @comment BSD
1380 @deftypefun void endhostent (void)
1381 This function closes the hosts database.
1382 @end deftypefun
1383
1384 @node Ports
1385 @subsection Internet Ports
1386 @cindex port number
1387
1388 A socket address in the Internet namespace consists of a machine's
1389 Internet address plus a @dfn{port number} which distinguishes the
1390 sockets on a given machine (for a given protocol).  Port numbers range
1391 from 0 to 65,535.
1392
1393 Port numbers less than @code{IPPORT_RESERVED} are reserved for standard
1394 servers, such as @code{finger} and @code{telnet}.  There is a database
1395 that keeps track of these, and you can use the @code{getservbyname}
1396 function to map a service name onto a port number; see @ref{Services
1397 Database}.
1398
1399 If you write a server that is not one of the standard ones defined in
1400 the database, you must choose a port number for it.  Use a number
1401 greater than @code{IPPORT_USERRESERVED}; such numbers are reserved for
1402 servers and won't ever be generated automatically by the system.
1403 Avoiding conflicts with servers being run by other users is up to you.
1404
1405 When you use a socket without specifying its address, the system
1406 generates a port number for it.  This number is between
1407 @code{IPPORT_RESERVED} and @code{IPPORT_USERRESERVED}.
1408
1409 On the Internet, it is actually legitimate to have two different
1410 sockets with the same port number, as long as they never both try to
1411 communicate with the same socket address (host address plus port
1412 number).  You shouldn't duplicate a port number except in special
1413 circumstances where a higher-level protocol requires it.  Normally,
1414 the system won't let you do it; @code{bind} normally insists on
1415 distinct port numbers.  To reuse a port number, you must set the
1416 socket option @code{SO_REUSEADDR}.  @xref{Socket-Level Options}.
1417
1418 @pindex netinet/in.h
1419 These macros are defined in the header file @file{netinet/in.h}.
1420
1421 @comment netinet/in.h
1422 @comment BSD
1423 @deftypevr Macro int IPPORT_RESERVED
1424 Port numbers less than @code{IPPORT_RESERVED} are reserved for
1425 superuser use.
1426 @end deftypevr
1427
1428 @comment netinet/in.h
1429 @comment BSD
1430 @deftypevr Macro int IPPORT_USERRESERVED
1431 Port numbers greater than or equal to @code{IPPORT_USERRESERVED} are
1432 reserved for explicit use; they will never be allocated automatically.
1433 @end deftypevr
1434
1435 @node Services Database
1436 @subsection The Services Database
1437 @cindex services database
1438 @cindex converting service name to port number
1439 @cindex converting port number to service name
1440
1441 @pindex /etc/services
1442 The database that keeps track of ``well-known'' services is usually
1443 either the file @file{/etc/services} or an equivalent from a name server.
1444 You can use these utilities, declared in @file{netdb.h}, to access
1445 the services database.
1446 @pindex netdb.h
1447
1448 @comment netdb.h
1449 @comment BSD
1450 @deftp {Data Type} {struct servent}
1451 This data type holds information about entries from the services database.
1452 It has the following members:
1453
1454 @table @code
1455 @item char *s_name
1456 This is the ``official'' name of the service.
1457
1458 @item char **s_aliases
1459 These are alternate names for the service, represented as an array of
1460 strings.  A null pointer terminates the array.
1461
1462 @item int s_port
1463 This is the port number for the service.  Port numbers are given in
1464 network byte order; see @ref{Byte Order}.
1465
1466 @item char *s_proto
1467 This is the name of the protocol to use with this service.
1468 @xref{Protocols Database}.
1469 @end table
1470 @end deftp
1471
1472 To get information about a particular service, use the
1473 @code{getservbyname} or @code{getservbyport} functions.  The information
1474 is returned in a statically-allocated structure; you must copy the
1475 information if you need to save it across calls.
1476
1477 @comment netdb.h
1478 @comment BSD
1479 @deftypefun {struct servent *} getservbyname (const char *@var{name}, const char *@var{proto})
1480 The @code{getservbyname} function returns information about the
1481 service named @var{name} using protocol @var{proto}.  If it can't find
1482 such a service, it returns a null pointer.
1483
1484 This function is useful for servers as well as for clients; servers
1485 use it to determine which port they should listen on (@pxref{Listening}).
1486 @end deftypefun
1487
1488 @comment netdb.h
1489 @comment BSD
1490 @deftypefun {struct servent *} getservbyport (int @var{port}, const char *@var{proto})
1491 The @code{getservbyport} function returns information about the
1492 service at port @var{port} using protocol @var{proto}.  If it can't
1493 find such a service, it returns a null pointer.
1494 @end deftypefun
1495
1496 @noindent
1497 You can also scan the services database using @code{setservent},
1498 @code{getservent} and @code{endservent}.  Be careful when using these
1499 functions because they are not reentrant.
1500
1501 @comment netdb.h
1502 @comment BSD
1503 @deftypefun void setservent (int @var{stayopen})
1504 This function opens the services database to begin scanning it.
1505
1506 If the @var{stayopen} argument is nonzero, this sets a flag so that
1507 subsequent calls to @code{getservbyname} or @code{getservbyport} will
1508 not close the database (as they usually would).  This makes for more
1509 efficiency if you call those functions several times, by avoiding
1510 reopening the database for each call.
1511 @end deftypefun
1512
1513 @comment netdb.h
1514 @comment BSD
1515 @deftypefun {struct servent *} getservent (void)
1516 This function returns the next entry in the services database.  If
1517 there are no more entries, it returns a null pointer.
1518 @end deftypefun
1519
1520 @comment netdb.h
1521 @comment BSD
1522 @deftypefun void endservent (void)
1523 This function closes the services database.
1524 @end deftypefun
1525
1526 @node Byte Order
1527 @subsection Byte Order Conversion
1528 @cindex byte order conversion, for socket
1529 @cindex converting byte order
1530
1531 @cindex big-endian
1532 @cindex little-endian
1533 Different kinds of computers use different conventions for the
1534 ordering of bytes within a word.  Some computers put the most
1535 significant byte within a word first (this is called ``big-endian''
1536 order), and others put it last (``little-endian'' order).
1537
1538 @cindex network byte order
1539 So that machines with different byte order conventions can
1540 communicate, the Internet protocols specify a canonical byte order
1541 convention for data transmitted over the network.  This is known
1542 as @dfn{network byte order}.
1543
1544 When establishing an Internet socket connection, you must make sure that
1545 the data in the @code{sin_port} and @code{sin_addr} members of the
1546 @code{sockaddr_in} structure are represented in network byte order.
1547 If you are encoding integer data in the messages sent through the
1548 socket, you should convert this to network byte order too.  If you don't
1549 do this, your program may fail when running on or talking to other kinds
1550 of machines.
1551
1552 If you use @code{getservbyname} and @code{gethostbyname} or
1553 @code{inet_addr} to get the port number and host address, the values are
1554 already in network byte order, and you can copy them directly into
1555 the @code{sockaddr_in} structure.
1556
1557 Otherwise, you have to convert the values explicitly.  Use @code{htons}
1558 and @code{ntohs} to convert values for the @code{sin_port} member.  Use
1559 @code{htonl} and @code{ntohl} to convert IPv4 addresses for the
1560 @code{sin_addr} member.  (Remember, @code{struct in_addr} is equivalent
1561 to @code{uint32_t}.)  These functions are declared in
1562 @file{netinet/in.h}.
1563 @pindex netinet/in.h
1564
1565 @comment netinet/in.h
1566 @comment BSD
1567 @deftypefun {uint16_t} htons (uint16_t @var{hostshort})
1568 This function converts the @code{uint16_t} integer @var{hostshort} from
1569 host byte order to network byte order.
1570 @end deftypefun
1571
1572 @comment netinet/in.h
1573 @comment BSD
1574 @deftypefun {uint16_t} ntohs (uint16_t @var{netshort})
1575 This function converts the @code{uint16_t} integer @var{netshort} from
1576 network byte order to host byte order.
1577 @end deftypefun
1578
1579 @comment netinet/in.h
1580 @comment BSD
1581 @deftypefun {uint32_t} htonl (uint32_t @var{hostlong})
1582 This function converts the @code{uint32_t} integer @var{hostlong} from
1583 host byte order to network byte order.
1584
1585 This is used for IPv4 Internet addresses.
1586 @end deftypefun
1587
1588 @comment netinet/in.h
1589 @comment BSD
1590 @deftypefun {uint32_t} ntohl (uint32_t @var{netlong})
1591 This function converts the @code{uint32_t} integer @var{netlong} from
1592 network byte order to host byte order.
1593
1594 This is used for IPv4 Internet addresses.
1595 @end deftypefun
1596
1597 @node Protocols Database
1598 @subsection Protocols Database
1599 @cindex protocols database
1600
1601 The communications protocol used with a socket controls low-level
1602 details of how data are exchanged.  For example, the protocol implements
1603 things like checksums to detect errors in transmissions, and routing
1604 instructions for messages.  Normal user programs have little reason to
1605 mess with these details directly.
1606
1607 @cindex TCP (Internet protocol)
1608 The default communications protocol for the Internet namespace depends on
1609 the communication style.  For stream communication, the default is TCP
1610 (``transmission control protocol'').  For datagram communication, the
1611 default is UDP (``user datagram protocol'').  For reliable datagram
1612 communication, the default is RDP (``reliable datagram protocol'').
1613 You should nearly always use the default.
1614
1615 @pindex /etc/protocols
1616 Internet protocols are generally specified by a name instead of a
1617 number.  The network protocols that a host knows about are stored in a
1618 database.  This is usually either derived from the file
1619 @file{/etc/protocols}, or it may be an equivalent provided by a name
1620 server.  You look up the protocol number associated with a named
1621 protocol in the database using the @code{getprotobyname} function.
1622
1623 Here are detailed descriptions of the utilities for accessing the
1624 protocols database.  These are declared in @file{netdb.h}.
1625 @pindex netdb.h
1626
1627 @comment netdb.h
1628 @comment BSD
1629 @deftp {Data Type} {struct protoent}
1630 This data type is used to represent entries in the network protocols
1631 database.  It has the following members:
1632
1633 @table @code
1634 @item char *p_name
1635 This is the official name of the protocol.
1636
1637 @item char **p_aliases
1638 These are alternate names for the protocol, specified as an array of
1639 strings.  The last element of the array is a null pointer.
1640
1641 @item int p_proto
1642 This is the protocol number (in host byte order); use this member as the
1643 @var{protocol} argument to @code{socket}.
1644 @end table
1645 @end deftp
1646
1647 You can use @code{getprotobyname} and @code{getprotobynumber} to search
1648 the protocols database for a specific protocol.  The information is
1649 returned in a statically-allocated structure; you must copy the
1650 information if you need to save it across calls.
1651
1652 @comment netdb.h
1653 @comment BSD
1654 @deftypefun {struct protoent *} getprotobyname (const char *@var{name})
1655 The @code{getprotobyname} function returns information about the
1656 network protocol named @var{name}.  If there is no such protocol, it
1657 returns a null pointer.
1658 @end deftypefun
1659
1660 @comment netdb.h
1661 @comment BSD
1662 @deftypefun {struct protoent *} getprotobynumber (int @var{protocol})
1663 The @code{getprotobynumber} function returns information about the
1664 network protocol with number @var{protocol}.  If there is no such
1665 protocol, it returns a null pointer.
1666 @end deftypefun
1667
1668 You can also scan the whole protocols database one protocol at a time by
1669 using @code{setprotoent}, @code{getprotoent} and @code{endprotoent}.
1670 Be careful when using these functions because they are not reentrant.
1671
1672 @comment netdb.h
1673 @comment BSD
1674 @deftypefun void setprotoent (int @var{stayopen})
1675 This function opens the protocols database to begin scanning it.
1676
1677 If the @var{stayopen} argument is nonzero, this sets a flag so that
1678 subsequent calls to @code{getprotobyname} or @code{getprotobynumber} will
1679 not close the database (as they usually would).  This makes for more
1680 efficiency if you call those functions several times, by avoiding
1681 reopening the database for each call.
1682 @end deftypefun
1683
1684 @comment netdb.h
1685 @comment BSD
1686 @deftypefun {struct protoent *} getprotoent (void)
1687 This function returns the next entry in the protocols database.  It
1688 returns a null pointer if there are no more entries.
1689 @end deftypefun
1690
1691 @comment netdb.h
1692 @comment BSD
1693 @deftypefun void endprotoent (void)
1694 This function closes the protocols database.
1695 @end deftypefun
1696
1697 @node Inet Example
1698 @subsection Internet Socket Example
1699
1700 Here is an example showing how to create and name a socket in the
1701 Internet namespace.  The newly created socket exists on the machine that
1702 the program is running on.  Rather than finding and using the machine's
1703 Internet address, this example specifies @code{INADDR_ANY} as the host
1704 address; the system replaces that with the machine's actual address.
1705
1706 @smallexample
1707 @include mkisock.c.texi
1708 @end smallexample
1709
1710 Here is another example, showing how you can fill in a @code{sockaddr_in}
1711 structure, given a host name string and a port number:
1712
1713 @smallexample
1714 @include isockad.c.texi
1715 @end smallexample
1716
1717 @node Misc Namespaces
1718 @section Other Namespaces
1719
1720 @vindex PF_NS
1721 @vindex PF_ISO
1722 @vindex PF_CCITT
1723 @vindex PF_IMPLINK
1724 @vindex PF_ROUTE
1725 Certain other namespaces and associated protocol families are supported
1726 but not documented yet because they are not often used.  @code{PF_NS}
1727 refers to the Xerox Network Software protocols.  @code{PF_ISO} stands
1728 for Open Systems Interconnect.  @code{PF_CCITT} refers to protocols from
1729 CCITT.  @file{socket.h} defines these symbols and others naming protocols
1730 not actually implemented.
1731
1732 @code{PF_IMPLINK} is used for communicating between hosts and Internet
1733 Message Processors.  For information on this and @code{PF_ROUTE}, an
1734 occasionally-used local area routing protocol, see the GNU Hurd Manual
1735 (to appear in the future).
1736
1737 @node Open/Close Sockets
1738 @section Opening and Closing Sockets
1739
1740 This section describes the actual library functions for opening and
1741 closing sockets.  The same functions work for all namespaces and
1742 connection styles.
1743
1744 @menu
1745 * Creating a Socket::           How to open a socket.
1746 * Closing a Socket::            How to close a socket.
1747 * Socket Pairs::                These are created like pipes.
1748 @end menu
1749
1750 @node Creating a Socket
1751 @subsection Creating a Socket
1752 @cindex creating a socket
1753 @cindex socket, creating
1754 @cindex opening a socket
1755
1756 The primitive for creating a socket is the @code{socket} function,
1757 declared in @file{sys/socket.h}.
1758 @pindex sys/socket.h
1759
1760 @comment sys/socket.h
1761 @comment BSD
1762 @deftypefun int socket (int @var{namespace}, int @var{style}, int @var{protocol})
1763 This function creates a socket and specifies communication style
1764 @var{style}, which should be one of the socket styles listed in
1765 @ref{Communication Styles}.  The @var{namespace} argument specifies
1766 the namespace; it must be @code{PF_LOCAL} (@pxref{Local Namespace}) or
1767 @code{PF_INET} (@pxref{Internet Namespace}).  @var{protocol}
1768 designates the specific protocol (@pxref{Socket Concepts}); zero is
1769 usually right for @var{protocol}.
1770
1771 The return value from @code{socket} is the file descriptor for the new
1772 socket, or @code{-1} in case of error.  The following @code{errno} error
1773 conditions are defined for this function:
1774
1775 @table @code
1776 @item EPROTONOSUPPORT
1777 The @var{protocol} or @var{style} is not supported by the
1778 @var{namespace} specified.
1779
1780 @item EMFILE
1781 The process already has too many file descriptors open.
1782
1783 @item ENFILE
1784 The system already has too many file descriptors open.
1785
1786 @item EACCESS
1787 The process does not have the privilege to create a socket of the specified
1788 @var{style} or @var{protocol}.
1789
1790 @item ENOBUFS
1791 The system ran out of internal buffer space.
1792 @end table
1793
1794 The file descriptor returned by the @code{socket} function supports both
1795 read and write operations.  However, like pipes, sockets do not support file
1796 positioning operations.
1797 @end deftypefun
1798
1799 For examples of how to call the @code{socket} function,
1800 see @ref{Local Socket Example}, or @ref{Inet Example}.
1801
1802
1803 @node Closing a Socket
1804 @subsection Closing a Socket
1805 @cindex socket, closing
1806 @cindex closing a socket
1807 @cindex shutting down a socket
1808 @cindex socket shutdown
1809
1810 When you have finished using a socket, you can simply close its
1811 file descriptor with @code{close}; see @ref{Opening and Closing Files}.
1812 If there is still data waiting to be transmitted over the connection,
1813 normally @code{close} tries to complete this transmission.  You
1814 can control this behavior using the @code{SO_LINGER} socket option to
1815 specify a timeout period; see @ref{Socket Options}.
1816
1817 @pindex sys/socket.h
1818 You can also shut down only reception or transmission on a
1819 connection by calling @code{shutdown}, which is declared in
1820 @file{sys/socket.h}.
1821
1822 @comment sys/socket.h
1823 @comment BSD
1824 @deftypefun int shutdown (int @var{socket}, int @var{how})
1825 The @code{shutdown} function shuts down the connection of socket
1826 @var{socket}.  The argument @var{how} specifies what action to
1827 perform:
1828
1829 @table @code
1830 @item 0
1831 Stop receiving data for this socket.  If further data arrives,
1832 reject it.
1833
1834 @item 1
1835 Stop trying to transmit data from this socket.  Discard any data
1836 waiting to be sent.  Stop looking for acknowledgement of data already
1837 sent; don't retransmit it if it is lost.
1838
1839 @item 2
1840 Stop both reception and transmission.
1841 @end table
1842
1843 The return value is @code{0} on success and @code{-1} on failure.  The
1844 following @code{errno} error conditions are defined for this function:
1845
1846 @table @code
1847 @item EBADF
1848 @var{socket} is not a valid file descriptor.
1849
1850 @item ENOTSOCK
1851 @var{socket} is not a socket.
1852
1853 @item ENOTCONN
1854 @var{socket} is not connected.
1855 @end table
1856 @end deftypefun
1857
1858 @node Socket Pairs
1859 @subsection Socket Pairs
1860 @cindex creating a socket pair
1861 @cindex socket pair
1862 @cindex opening a socket pair
1863
1864 @pindex sys/socket.h
1865 A @dfn{socket pair} consists of a pair of connected (but unnamed)
1866 sockets.  It is very similar to a pipe and is used in much the same
1867 way.  Socket pairs are created with the @code{socketpair} function,
1868 declared in @file{sys/socket.h}.  A socket pair is much like a pipe; the
1869 main difference is that the socket pair is bidirectional, whereas the
1870 pipe has one input-only end and one output-only end (@pxref{Pipes and
1871 FIFOs}).
1872
1873 @comment sys/socket.h
1874 @comment BSD
1875 @deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})
1876 This function creates a socket pair, returning the file descriptors in
1877 @code{@var{filedes}[0]} and @code{@var{filedes}[1]}.  The socket pair
1878 is a full-duplex communications channel, so that both reading and writing
1879 may be performed at either end.
1880
1881 The @var{namespace}, @var{style} and @var{protocol} arguments are
1882 interpreted as for the @code{socket} function.  @var{style} should be
1883 one of the communication styles listed in @ref{Communication Styles}.
1884 The @var{namespace} argument specifies the namespace, which must be
1885 @code{AF_LOCAL} (@pxref{Local Namespace}); @var{protocol} specifies the
1886 communications protocol, but zero is the only meaningful value.
1887
1888 If @var{style} specifies a connectionless communication style, then
1889 the two sockets you get are not @emph{connected}, strictly speaking,
1890 but each of them knows the other as the default destination address,
1891 so they can send packets to each other.
1892
1893 The @code{socketpair} function returns @code{0} on success and @code{-1}
1894 on failure.  The following @code{errno} error conditions are defined
1895 for this function:
1896
1897 @table @code
1898 @item EMFILE
1899 The process has too many file descriptors open.
1900
1901 @item EAFNOSUPPORT
1902 The specified namespace is not supported.
1903
1904 @item EPROTONOSUPPORT
1905 The specified protocol is not supported.
1906
1907 @item EOPNOTSUPP
1908 The specified protocol does not support the creation of socket pairs.
1909 @end table
1910 @end deftypefun
1911
1912 @node Connections
1913 @section Using Sockets with Connections
1914
1915 @cindex connection
1916 @cindex client
1917 @cindex server
1918 The most common communication styles involve making a connection to a
1919 particular other socket, and then exchanging data with that socket
1920 over and over.  Making a connection is asymmetric; one side (the
1921 @dfn{client}) acts to request a connection, while the other side (the
1922 @dfn{server}) makes a socket and waits for the connection request.
1923
1924 @iftex
1925 @itemize @bullet
1926 @item
1927 @ref{Connecting}, describes what the client program must do to
1928 initiate a connection with a server.
1929
1930 @item
1931 @ref{Listening} and @ref{Accepting Connections} describe what the
1932 server program must do to wait for and act upon connection requests
1933 from clients.
1934
1935 @item
1936 @ref{Transferring Data}, describes how data are transferred through the
1937 connected socket.
1938 @end itemize
1939 @end iftex
1940
1941 @menu
1942 * Connecting::               What the client program must do.
1943 * Listening::                How a server program waits for requests.
1944 * Accepting Connections::    What the server does when it gets a request.
1945 * Who is Connected::         Getting the address of the
1946                                 other side of a connection.
1947 * Transferring Data::        How to send and receive data.
1948 * Byte Stream Example::      An example program: a client for communicating
1949                               over a byte stream socket in the Internet namespace.
1950 * Server Example::           A corresponding server program.
1951 * Out-of-Band Data::         This is an advanced feature.
1952 @end menu
1953
1954 @node Connecting
1955 @subsection Making a Connection
1956 @cindex connecting a socket
1957 @cindex socket, connecting
1958 @cindex socket, initiating a connection
1959 @cindex socket, client actions
1960
1961 In making a connection, the client makes a connection while the server
1962 waits for and accepts the connection.  Here we discuss what the client
1963 program must do with the @code{connect} function, which is declared in
1964 @file{sys/socket.h}.
1965
1966 @comment sys/socket.h
1967 @comment BSD
1968 @deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
1969 The @code{connect} function initiates a connection from the socket
1970 with file descriptor @var{socket} to the socket whose address is
1971 specified by the @var{addr} and @var{length} arguments.  (This socket
1972 is typically on another machine, and it must be already set up as a
1973 server.)  @xref{Socket Addresses}, for information about how these
1974 arguments are interpreted.
1975
1976 Normally, @code{connect} waits until the server responds to the request
1977 before it returns.  You can set nonblocking mode on the socket
1978 @var{socket} to make @code{connect} return immediately without waiting
1979 for the response.  @xref{File Status Flags}, for information about
1980 nonblocking mode.
1981 @c !!! how do you tell when it has finished connecting?  I suspect the
1982 @c way you do it is select for writing.
1983
1984 The normal return value from @code{connect} is @code{0}.  If an error
1985 occurs, @code{connect} returns @code{-1}.  The following @code{errno}
1986 error conditions are defined for this function:
1987
1988 @table @code
1989 @item EBADF
1990 The socket @var{socket} is not a valid file descriptor.
1991
1992 @item ENOTSOCK
1993 File descriptor @var{socket} is not a socket.
1994
1995 @item EADDRNOTAVAIL
1996 The specified address is not available on the remote machine.
1997
1998 @item EAFNOSUPPORT
1999 The namespace of the @var{addr} is not supported by this socket.
2000
2001 @item EISCONN
2002 The socket @var{socket} is already connected.
2003
2004 @item ETIMEDOUT
2005 The attempt to establish the connection timed out.
2006
2007 @item ECONNREFUSED
2008 The server has actively refused to establish the connection.
2009
2010 @item ENETUNREACH
2011 The network of the given @var{addr} isn't reachable from this host.
2012
2013 @item EADDRINUSE
2014 The socket address of the given @var{addr} is already in use.
2015
2016 @item EINPROGRESS
2017 The socket @var{socket} is non-blocking and the connection could not be
2018 established immediately.  You can determine when the connection is
2019 completely established with @code{select}; @pxref{Waiting for I/O}.
2020 Another @code{connect} call on the same socket, before the connection is
2021 completely established, will fail with @code{EALREADY}.
2022
2023 @item EALREADY
2024 The socket @var{socket} is non-blocking and already has a pending
2025 connection in progress (see @code{EINPROGRESS} above).
2026 @end table
2027
2028 This function is defined as a cancellation point in multi-threaded
2029 programs, so one has to be prepared for this and make sure that
2030 allocated resources (like memory, files descriptors, semaphores or
2031 whatever) are freed even if the thread is canceled.
2032 @c @xref{pthread_cleanup_push}, for a method how to do this.
2033 @end deftypefun
2034
2035 @node Listening
2036 @subsection Listening for Connections
2037 @cindex listening (sockets)
2038 @cindex sockets, server actions
2039 @cindex sockets, listening
2040
2041 Now let us consider what the server process must do to accept
2042 connections on a socket.  First it must use the @code{listen} function
2043 to enable connection requests on the socket, and then accept each
2044 incoming connection with a call to @code{accept} (@pxref{Accepting
2045 Connections}).  Once connection requests are enabled on a server socket,
2046 the @code{select} function reports when the socket has a connection
2047 ready to be accepted (@pxref{Waiting for I/O}).
2048
2049 The @code{listen} function is not allowed for sockets using
2050 connectionless communication styles.
2051
2052 You can write a network server that does not even start running until a
2053 connection to it is requested.  @xref{Inetd Servers}.
2054
2055 In the Internet namespace, there are no special protection mechanisms
2056 for controlling access to a port; any process on any machine
2057 can make a connection to your server.  If you want to restrict access to
2058 your server, make it examine the addresses associated with connection
2059 requests or implement some other handshaking or identification
2060 protocol.
2061
2062 In the local namespace, the ordinary file protection bits control who has
2063 access to connect to the socket.
2064
2065 @comment sys/socket.h
2066 @comment BSD
2067 @deftypefun int listen (int @var{socket}, unsigned int @var{n})
2068 The @code{listen} function enables the socket @var{socket} to accept
2069 connections, thus making it a server socket.
2070
2071 The argument @var{n} specifies the length of the queue for pending
2072 connections.  When the queue fills, new clients attempting to connect
2073 fail with @code{ECONNREFUSED} until the server calls @code{accept} to
2074 accept a connection from the queue.
2075
2076 The @code{listen} function returns @code{0} on success and @code{-1}
2077 on failure.  The following @code{errno} error conditions are defined
2078 for this function:
2079
2080 @table @code
2081 @item EBADF
2082 The argument @var{socket} is not a valid file descriptor.
2083
2084 @item ENOTSOCK
2085 The argument @var{socket} is not a socket.
2086
2087 @item EOPNOTSUPP
2088 The socket @var{socket} does not support this operation.
2089 @end table
2090 @end deftypefun
2091
2092 @node Accepting Connections
2093 @subsection Accepting Connections
2094 @cindex sockets, accepting connections
2095 @cindex accepting connections
2096
2097 When a server receives a connection request, it can complete the
2098 connection by accepting the request.  Use the function @code{accept}
2099 to do this.
2100
2101 A socket that has been established as a server can accept connection
2102 requests from multiple clients.  The server's original socket
2103 @emph{does not become part of the connection}; instead, @code{accept}
2104 makes a new socket which participates in the connection.
2105 @code{accept} returns the descriptor for this socket.  The server's
2106 original socket remains available for listening for further connection
2107 requests.
2108
2109 The number of pending connection requests on a server socket is finite.
2110 If connection requests arrive from clients faster than the server can
2111 act upon them, the queue can fill up and additional requests are refused
2112 with an @code{ECONNREFUSED} error.  You can specify the maximum length of
2113 this queue as an argument to the @code{listen} function, although the
2114 system may also impose its own internal limit on the length of this
2115 queue.
2116
2117 @comment sys/socket.h
2118 @comment BSD
2119 @deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length_ptr})
2120 This function is used to accept a connection request on the server
2121 socket @var{socket}.
2122
2123 The @code{accept} function waits if there are no connections pending,
2124 unless the socket @var{socket} has nonblocking mode set.  (You can use
2125 @code{select} to wait for a pending connection, with a nonblocking
2126 socket.)  @xref{File Status Flags}, for information about nonblocking
2127 mode.
2128
2129 The @var{addr} and @var{length-ptr} arguments are used to return
2130 information about the name of the client socket that initiated the
2131 connection.  @xref{Socket Addresses}, for information about the format
2132 of the information.
2133
2134 Accepting a connection does not make @var{socket} part of the
2135 connection.  Instead, it creates a new socket which becomes
2136 connected.  The normal return value of @code{accept} is the file
2137 descriptor for the new socket.
2138
2139 After @code{accept}, the original socket @var{socket} remains open and
2140 unconnected, and continues listening until you close it.  You can
2141 accept further connections with @var{socket} by calling @code{accept}
2142 again.
2143
2144 If an error occurs, @code{accept} returns @code{-1}.  The following
2145 @code{errno} error conditions are defined for this function:
2146
2147 @table @code
2148 @item EBADF
2149 The @var{socket} argument is not a valid file descriptor.
2150
2151 @item ENOTSOCK
2152 The descriptor @var{socket} argument is not a socket.
2153
2154 @item EOPNOTSUPP
2155 The descriptor @var{socket} does not support this operation.
2156
2157 @item EWOULDBLOCK
2158 @var{socket} has nonblocking mode set, and there are no pending
2159 connections immediately available.
2160 @end table
2161
2162 This function is defined as a cancellation point in multi-threaded
2163 programs, so one has to be prepared for this and make sure that
2164 allocated resources (like memory, files descriptors, semaphores or
2165 whatever) are freed even if the thread is canceled.
2166 @c @xref{pthread_cleanup_push}, for a method how to do this.
2167 @end deftypefun
2168
2169 The @code{accept} function is not allowed for sockets using
2170 connectionless communication styles.
2171
2172 @node Who is Connected
2173 @subsection Who is Connected to Me?
2174
2175 @comment sys/socket.h
2176 @comment BSD
2177 @deftypefun int getpeername (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
2178 The @code{getpeername} function returns the address of the socket that
2179 @var{socket} is connected to; it stores the address in the memory space
2180 specified by @var{addr} and @var{length-ptr}.  It stores the length of
2181 the address in @code{*@var{length-ptr}}.
2182
2183 @xref{Socket Addresses}, for information about the format of the
2184 address.  In some operating systems, @code{getpeername} works only for
2185 sockets in the Internet domain.
2186
2187 The return value is @code{0} on success and @code{-1} on error.  The
2188 following @code{errno} error conditions are defined for this function:
2189
2190 @table @code
2191 @item EBADF
2192 The argument @var{socket} is not a valid file descriptor.
2193
2194 @item ENOTSOCK
2195 The descriptor @var{socket} is not a socket.
2196
2197 @item ENOTCONN
2198 The socket @var{socket} is not connected.
2199
2200 @item ENOBUFS
2201 There are not enough internal buffers available.
2202 @end table
2203 @end deftypefun
2204
2205
2206 @node Transferring Data
2207 @subsection Transferring Data
2208 @cindex reading from a socket
2209 @cindex writing to a socket
2210
2211 Once a socket has been connected to a peer, you can use the ordinary
2212 @code{read} and @code{write} operations (@pxref{I/O Primitives}) to
2213 transfer data.  A socket is a two-way communications channel, so read
2214 and write operations can be performed at either end.
2215
2216 There are also some I/O modes that are specific to socket operations.
2217 In order to specify these modes, you must use the @code{recv} and
2218 @code{send} functions instead of the more generic @code{read} and
2219 @code{write} functions.  The @code{recv} and @code{send} functions take
2220 an additional argument which you can use to specify various flags to
2221 control special I/O modes.  For example, you can specify the
2222 @code{MSG_OOB} flag to read or write out-of-band data, the
2223 @code{MSG_PEEK} flag to peek at input, or the @code{MSG_DONTROUTE} flag
2224 to control inclusion of routing information on output.
2225
2226 @menu
2227 * Sending Data::                Sending data with @code{send}.
2228 * Receiving Data::              Reading data with @code{recv}.
2229 * Socket Data Options::         Using @code{send} and @code{recv}.
2230 @end menu
2231
2232 @node Sending Data
2233 @subsubsection Sending Data
2234
2235 @pindex sys/socket.h
2236 The @code{send} function is declared in the header file
2237 @file{sys/socket.h}.  If your @var{flags} argument is zero, you can just
2238 as well use @code{write} instead of @code{send}; see @ref{I/O
2239 Primitives}.  If the socket was connected but the connection has broken,
2240 you get a @code{SIGPIPE} signal for any use of @code{send} or
2241 @code{write} (@pxref{Miscellaneous Signals}).
2242
2243 @comment sys/socket.h
2244 @comment BSD
2245 @deftypefun int send (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2246 The @code{send} function is like @code{write}, but with the additional
2247 flags @var{flags}.  The possible values of @var{flags} are described
2248 in @ref{Socket Data Options}.
2249
2250 This function returns the number of bytes transmitted, or @code{-1} on
2251 failure.  If the socket is nonblocking, then @code{send} (like
2252 @code{write}) can return after sending just part of the data.
2253 @xref{File Status Flags}, for information about nonblocking mode.
2254
2255 Note, however, that a successful return value merely indicates that
2256 the message has been sent without error, not necessarily that it has
2257 been received without error.
2258
2259 The following @code{errno} error conditions are defined for this function:
2260
2261 @table @code
2262 @item EBADF
2263 The @var{socket} argument is not a valid file descriptor.
2264
2265 @item EINTR
2266 The operation was interrupted by a signal before any data was sent.
2267 @xref{Interrupted Primitives}.
2268
2269 @item ENOTSOCK
2270 The descriptor @var{socket} is not a socket.
2271
2272 @item EMSGSIZE
2273 The socket type requires that the message be sent atomically, but the
2274 message is too large for this to be possible.
2275
2276 @item EWOULDBLOCK
2277 Nonblocking mode has been set on the socket, and the write operation
2278 would block.  (Normally @code{send} blocks until the operation can be
2279 completed.)
2280
2281 @item ENOBUFS
2282 There is not enough internal buffer space available.
2283
2284 @item ENOTCONN
2285 You never connected this socket.
2286
2287 @item EPIPE
2288 This socket was connected but the connection is now broken.  In this
2289 case, @code{send} generates a @code{SIGPIPE} signal first; if that
2290 signal is ignored or blocked, or if its handler returns, then
2291 @code{send} fails with @code{EPIPE}.
2292 @end table
2293
2294 This function is defined as a cancellation point in multi-threaded
2295 programs, so one has to be prepared for this and make sure that
2296 allocated resources (like memory, files descriptors, semaphores or
2297 whatever) are freed even if the thread is canceled.
2298 @c @xref{pthread_cleanup_push}, for a method how to do this.
2299 @end deftypefun
2300
2301 @node Receiving Data
2302 @subsubsection Receiving Data
2303
2304 @pindex sys/socket.h
2305 The @code{recv} function is declared in the header file
2306 @file{sys/socket.h}.  If your @var{flags} argument is zero, you can
2307 just as well use @code{read} instead of @code{recv}; see @ref{I/O
2308 Primitives}.
2309
2310 @comment sys/socket.h
2311 @comment BSD
2312 @deftypefun int recv (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2313 The @code{recv} function is like @code{read}, but with the additional
2314 flags @var{flags}.  The possible values of @var{flags} are described
2315 in @ref{Socket Data Options}.
2316
2317 If nonblocking mode is set for @var{socket}, and no data are available to
2318 be read, @code{recv} fails immediately rather than waiting.  @xref{File
2319 Status Flags}, for information about nonblocking mode.
2320
2321 This function returns the number of bytes received, or @code{-1} on failure.
2322 The following @code{errno} error conditions are defined for this function:
2323
2324 @table @code
2325 @item EBADF
2326 The @var{socket} argument is not a valid file descriptor.
2327
2328 @item ENOTSOCK
2329 The descriptor @var{socket} is not a socket.
2330
2331 @item EWOULDBLOCK
2332 Nonblocking mode has been set on the socket, and the read operation
2333 would block.  (Normally, @code{recv} blocks until there is input
2334 available to be read.)
2335
2336 @item EINTR
2337 The operation was interrupted by a signal before any data was read.
2338 @xref{Interrupted Primitives}.
2339
2340 @item ENOTCONN
2341 You never connected this socket.
2342 @end table
2343
2344 This function is defined as a cancellation point in multi-threaded
2345 programs, so one has to be prepared for this and make sure that
2346 allocated resources (like memory, files descriptors, semaphores or
2347 whatever) are freed even if the thread is canceled.
2348 @c @xref{pthread_cleanup_push}, for a method how to do this.
2349 @end deftypefun
2350
2351 @node Socket Data Options
2352 @subsubsection Socket Data Options
2353
2354 @pindex sys/socket.h
2355 The @var{flags} argument to @code{send} and @code{recv} is a bit
2356 mask.  You can bitwise-OR the values of the following macros together
2357 to obtain a value for this argument.  All are defined in the header
2358 file @file{sys/socket.h}.
2359
2360 @comment sys/socket.h
2361 @comment BSD
2362 @deftypevr Macro int MSG_OOB
2363 Send or receive out-of-band data.  @xref{Out-of-Band Data}.
2364 @end deftypevr
2365
2366 @comment sys/socket.h
2367 @comment BSD
2368 @deftypevr Macro int MSG_PEEK
2369 Look at the data but don't remove it from the input queue.  This is
2370 only meaningful with input functions such as @code{recv}, not with
2371 @code{send}.
2372 @end deftypevr
2373
2374 @comment sys/socket.h
2375 @comment BSD
2376 @deftypevr Macro int MSG_DONTROUTE
2377 Don't include routing information in the message.  This is only
2378 meaningful with output operations, and is usually only of interest for
2379 diagnostic or routing programs.  We don't try to explain it here.
2380 @end deftypevr
2381
2382 @node Byte Stream Example
2383 @subsection Byte Stream Socket Example
2384
2385 Here is an example client program that makes a connection for a byte
2386 stream socket in the Internet namespace.  It doesn't do anything
2387 particularly interesting once it has connected to the server; it just
2388 sends a text string to the server and exits.
2389
2390 This program uses @code{init_sockaddr} to set up the socket address; see
2391 @ref{Inet Example}.
2392
2393 @smallexample
2394 @include inetcli.c.texi
2395 @end smallexample
2396
2397 @node Server Example
2398 @subsection Byte Stream Connection Server Example
2399
2400 The server end is much more complicated.  Since we want to allow
2401 multiple clients to be connected to the server at the same time, it
2402 would be incorrect to wait for input from a single client by simply
2403 calling @code{read} or @code{recv}.  Instead, the right thing to do is
2404 to use @code{select} (@pxref{Waiting for I/O}) to wait for input on
2405 all of the open sockets.  This also allows the server to deal with
2406 additional connection requests.
2407
2408 This particular server doesn't do anything interesting once it has
2409 gotten a message from a client.  It does close the socket for that
2410 client when it detects an end-of-file condition (resulting from the
2411 client shutting down its end of the connection).
2412
2413 This program uses @code{make_socket} to set up the socket address; see
2414 @ref{Inet Example}.
2415
2416 @smallexample
2417 @include inetsrv.c.texi
2418 @end smallexample
2419
2420 @node Out-of-Band Data
2421 @subsection Out-of-Band Data
2422
2423 @cindex out-of-band data
2424 @cindex high-priority data
2425 Streams with connections permit @dfn{out-of-band} data that is
2426 delivered with higher priority than ordinary data.  Typically the
2427 reason for sending out-of-band data is to send notice of an
2428 exceptional condition.  To send out-of-band data use
2429 @code{send}, specifying the flag @code{MSG_OOB} (@pxref{Sending
2430 Data}).
2431
2432 Out-of-band data are received with higher priority because the
2433 receiving process need not read it in sequence; to read the next
2434 available out-of-band data, use @code{recv} with the @code{MSG_OOB}
2435 flag (@pxref{Receiving Data}).  Ordinary read operations do not read
2436 out-of-band data; they read only ordinary data.
2437
2438 @cindex urgent socket condition
2439 When a socket finds that out-of-band data are on their way, it sends a
2440 @code{SIGURG} signal to the owner process or process group of the
2441 socket.  You can specify the owner using the @code{F_SETOWN} command
2442 to the @code{fcntl} function; see @ref{Interrupt Input}.  You must
2443 also establish a handler for this signal, as described in @ref{Signal
2444 Handling}, in order to take appropriate action such as reading the
2445 out-of-band data.
2446
2447 Alternatively, you can test for pending out-of-band data, or wait
2448 until there is out-of-band data, using the @code{select} function; it
2449 can wait for an exceptional condition on the socket.  @xref{Waiting
2450 for I/O}, for more information about @code{select}.
2451
2452 Notification of out-of-band data (whether with @code{SIGURG} or with
2453 @code{select}) indicates that out-of-band data are on the way; the data
2454 may not actually arrive until later.  If you try to read the
2455 out-of-band data before it arrives, @code{recv} fails with an
2456 @code{EWOULDBLOCK} error.
2457
2458 Sending out-of-band data automatically places a ``mark'' in the stream
2459 of ordinary data, showing where in the sequence the out-of-band data
2460 ``would have been''.  This is useful when the meaning of out-of-band
2461 data is ``cancel everything sent so far''.  Here is how you can test,
2462 in the receiving process, whether any ordinary data was sent before
2463 the mark:
2464
2465 @smallexample
2466 success = ioctl (socket, SIOCATMARK, &atmark);
2467 @end smallexample
2468
2469 The @code{integer} variable @var{atmark} is set to a nonzero value if
2470 the socket's read pointer has reached the ``mark''.
2471
2472 @c Posix  1.g specifies sockatmark for this ioctl.  sockatmark is not
2473 @c implemented yet.
2474
2475 Here's a function to discard any ordinary data preceding the
2476 out-of-band mark:
2477
2478 @smallexample
2479 int
2480 discard_until_mark (int socket)
2481 @{
2482   while (1)
2483     @{
2484       /* @r{This is not an arbitrary limit; any size will do.}  */
2485       char buffer[1024];
2486       int atmark, success;
2487
2488       /* @r{If we have reached the mark, return.}  */
2489       success = ioctl (socket, SIOCATMARK, &atmark);
2490       if (success < 0)
2491         perror ("ioctl");
2492       if (result)
2493         return;
2494
2495       /* @r{Otherwise, read a bunch of ordinary data and discard it.}
2496          @r{This is guaranteed not to read past the mark}
2497          @r{if it starts before the mark.}  */
2498       success = read (socket, buffer, sizeof buffer);
2499       if (success < 0)
2500         perror ("read");
2501     @}
2502 @}
2503 @end smallexample
2504
2505 If you don't want to discard the ordinary data preceding the mark, you
2506 may need to read some of it anyway, to make room in internal system
2507 buffers for the out-of-band data.  If you try to read out-of-band data
2508 and get an @code{EWOULDBLOCK} error, try reading some ordinary data
2509 (saving it so that you can use it when you want it) and see if that
2510 makes room.  Here is an example:
2511
2512 @smallexample
2513 struct buffer
2514 @{
2515   char *buf;
2516   int size;
2517   struct buffer *next;
2518 @};
2519
2520 /* @r{Read the out-of-band data from SOCKET and return it}
2521    @r{as a `struct buffer', which records the address of the data}
2522    @r{and its size.}
2523
2524    @r{It may be necessary to read some ordinary data}
2525    @r{in order to make room for the out-of-band data.}
2526    @r{If so, the ordinary data are saved as a chain of buffers}
2527    @r{found in the `next' field of the value.}  */
2528
2529 struct buffer *
2530 read_oob (int socket)
2531 @{
2532   struct buffer *tail = 0;
2533   struct buffer *list = 0;
2534
2535   while (1)
2536     @{
2537       /* @r{This is an arbitrary limit.}
2538          @r{Does anyone know how to do this without a limit?}  */
2539 #define BUF_SZ 1024
2540       char *buf = (char *) xmalloc (BUF_SZ);
2541       int success;
2542       int atmark;
2543
2544       /* @r{Try again to read the out-of-band data.}  */
2545       success = recv (socket, buf, BUF_SZ, MSG_OOB);
2546       if (success >= 0)
2547         @{
2548           /* @r{We got it, so return it.}  */
2549           struct buffer *link
2550             = (struct buffer *) xmalloc (sizeof (struct buffer));
2551           link->buf = buf;
2552           link->size = success;
2553           link->next = list;
2554           return link;
2555         @}
2556
2557       /* @r{If we fail, see if we are at the mark.}  */
2558       success = ioctl (socket, SIOCATMARK, &atmark);
2559       if (success < 0)
2560         perror ("ioctl");
2561       if (atmark)
2562         @{
2563           /* @r{At the mark; skipping past more ordinary data cannot help.}
2564              @r{So just wait a while.}  */
2565           sleep (1);
2566           continue;
2567         @}
2568
2569       /* @r{Otherwise, read a bunch of ordinary data and save it.}
2570          @r{This is guaranteed not to read past the mark}
2571          @r{if it starts before the mark.}  */
2572       success = read (socket, buf, BUF_SZ);
2573       if (success < 0)
2574         perror ("read");
2575
2576       /* @r{Save this data in the buffer list.}  */
2577       @{
2578         struct buffer *link
2579           = (struct buffer *) xmalloc (sizeof (struct buffer));
2580         link->buf = buf;
2581         link->size = success;
2582
2583         /* @r{Add the new link to the end of the list.}  */
2584         if (tail)
2585           tail->next = link;
2586         else
2587           list = link;
2588         tail = link;
2589       @}
2590     @}
2591 @}
2592 @end smallexample
2593
2594 @node Datagrams
2595 @section Datagram Socket Operations
2596
2597 @cindex datagram socket
2598 This section describes how to use communication styles that don't use
2599 connections (styles @code{SOCK_DGRAM} and @code{SOCK_RDM}).  Using
2600 these styles, you group data into packets and each packet is an
2601 independent communication.  You specify the destination for each
2602 packet individually.
2603
2604 Datagram packets are like letters: you send each one independently
2605 with its own destination address, and they may arrive in the wrong
2606 order or not at all.
2607
2608 The @code{listen} and @code{accept} functions are not allowed for
2609 sockets using connectionless communication styles.
2610
2611 @menu
2612 * Sending Datagrams::    Sending packets on a datagram socket.
2613 * Receiving Datagrams::  Receiving packets on a datagram socket.
2614 * Datagram Example::     An example program: packets sent over a
2615                            datagram socket in the local namespace.
2616 * Example Receiver::     Another program, that receives those packets.
2617 @end menu
2618
2619 @node Sending Datagrams
2620 @subsection Sending Datagrams
2621 @cindex sending a datagram
2622 @cindex transmitting datagrams
2623 @cindex datagrams, transmitting
2624
2625 @pindex sys/socket.h
2626 The normal way of sending data on a datagram socket is by using the
2627 @code{sendto} function, declared in @file{sys/socket.h}.
2628
2629 You can call @code{connect} on a datagram socket, but this only
2630 specifies a default destination for further data transmission on the
2631 socket.  When a socket has a default destination you can use
2632 @code{send} (@pxref{Sending Data}) or even @code{write} (@pxref{I/O
2633 Primitives}) to send a packet there.  You can cancel the default
2634 destination by calling @code{connect} using an address format of
2635 @code{AF_UNSPEC} in the @var{addr} argument.  @xref{Connecting}, for
2636 more information about the @code{connect} function.
2637
2638 @comment sys/socket.h
2639 @comment BSD
2640 @deftypefun int sendto (int @var{socket}, void *@var{buffer}. size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, socklen_t @var{length})
2641 The @code{sendto} function transmits the data in the @var{buffer}
2642 through the socket @var{socket} to the destination address specified
2643 by the @var{addr} and @var{length} arguments.  The @var{size} argument
2644 specifies the number of bytes to be transmitted.
2645
2646 The @var{flags} are interpreted the same way as for @code{send}; see
2647 @ref{Socket Data Options}.
2648
2649 The return value and error conditions are also the same as for
2650 @code{send}, but you cannot rely on the system to detect errors and
2651 report them; the most common error is that the packet is lost or there
2652 is no-one at the specified address to receive it, and the operating
2653 system on your machine usually does not know this.
2654
2655 It is also possible for one call to @code{sendto} to report an error
2656 owing to a problem related to a previous call.
2657
2658 This function is defined as a cancellation point in multi-threaded
2659 programs, so one has to be prepared for this and make sure that
2660 allocated resources (like memory, files descriptors, semaphores or
2661 whatever) are freed even if the thread is canceled.
2662 @c @xref{pthread_cleanup_push}, for a method how to do this.
2663 @end deftypefun
2664
2665 @node Receiving Datagrams
2666 @subsection Receiving Datagrams
2667 @cindex receiving datagrams
2668
2669 The @code{recvfrom} function reads a packet from a datagram socket and
2670 also tells you where it was sent from.  This function is declared in
2671 @file{sys/socket.h}.
2672
2673 @comment sys/socket.h
2674 @comment BSD
2675 @deftypefun int recvfrom (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
2676 The @code{recvfrom} function reads one packet from the socket
2677 @var{socket} into the buffer @var{buffer}.  The @var{size} argument
2678 specifies the maximum number of bytes to be read.
2679
2680 If the packet is longer than @var{size} bytes, then you get the first
2681 @var{size} bytes of the packet and the rest of the packet is lost.
2682 There's no way to read the rest of the packet.  Thus, when you use a
2683 packet protocol, you must always know how long a packet to expect.
2684
2685 The @var{addr} and @var{length-ptr} arguments are used to return the
2686 address where the packet came from.  @xref{Socket Addresses}.  For a
2687 socket in the local domain the address information won't be meaningful,
2688 since you can't read the address of such a socket (@pxref{Local
2689 Namespace}).  You can specify a null pointer as the @var{addr} argument
2690 if you are not interested in this information.
2691
2692 The @var{flags} are interpreted the same way as for @code{recv}
2693 (@pxref{Socket Data Options}).  The return value and error conditions
2694 are also the same as for @code{recv}.
2695
2696 This function is defined as a cancellation point in multi-threaded
2697 programs, so one has to be prepared for this and make sure that
2698 allocated resources (like memory, files descriptors, semaphores or
2699 whatever) are freed even if the thread is canceled.
2700 @c @xref{pthread_cleanup_push}, for a method how to do this.
2701 @end deftypefun
2702
2703 You can use plain @code{recv} (@pxref{Receiving Data}) instead of
2704 @code{recvfrom} if you don't need to find out who sent the packet
2705 (either because you know where it should come from or because you
2706 treat all possible senders alike).  Even @code{read} can be used if
2707 you don't want to specify @var{flags} (@pxref{I/O Primitives}).
2708
2709 @ignore
2710 @c sendmsg and recvmsg are like readv and writev in that they
2711 @c use a series of buffers.  It's not clear this is worth
2712 @c supporting or that we support them.
2713 @c !!! they can do more; it is hairy
2714
2715 @comment sys/socket.h
2716 @comment BSD
2717 @deftp {Data Type} {struct msghdr}
2718 @end deftp
2719
2720 @comment sys/socket.h
2721 @comment BSD
2722 @deftypefun int sendmsg (int @var{socket}, const struct msghdr *@var{message}, int @var{flags})
2723
2724 This function is defined as a cancellation point in multi-threaded
2725 programs, so one has to be prepared for this and make sure that
2726 allocated resources (like memory, files descriptors, semaphores or
2727 whatever) are freed even if the thread is cancel.
2728 @c @xref{pthread_cleanup_push}, for a method how to do this.
2729 @end deftypefun
2730
2731 @comment sys/socket.h
2732 @comment BSD
2733 @deftypefun int recvmsg (int @var{socket}, struct msghdr *@var{message}, int @var{flags})
2734
2735 This function is defined as a cancellation point in multi-threaded
2736 programs, so one has to be prepared for this and make sure that
2737 allocated resources (like memory, files descriptors, semaphores or
2738 whatever) are freed even if the thread is canceled.
2739 @c @xref{pthread_cleanup_push}, for a method how to do this.
2740 @end deftypefun
2741 @end ignore
2742
2743 @node Datagram Example
2744 @subsection Datagram Socket Example
2745
2746 Here is a set of example programs that send messages over a datagram
2747 stream in the local namespace.  Both the client and server programs use
2748 the @code{make_named_socket} function that was presented in @ref{Local
2749 Socket Example}, to create and name their sockets.
2750
2751 First, here is the server program.  It sits in a loop waiting for
2752 messages to arrive, bouncing each message back to the sender.
2753 Obviously this isn't a particularly useful program, but it does show
2754 the general ideas involved.
2755
2756 @smallexample
2757 @include filesrv.c.texi
2758 @end smallexample
2759
2760 @node Example Receiver
2761 @subsection Example of Reading Datagrams
2762
2763 Here is the client program corresponding to the server above.
2764
2765 It sends a datagram to the server and then waits for a reply.  Notice
2766 that the socket for the client (as well as for the server) in this
2767 example has to be given a name.  This is so that the server can direct
2768 a message back to the client.  Since the socket has no associated
2769 connection state, the only way the server can do this is by
2770 referencing the name of the client.
2771
2772 @smallexample
2773 @include filecli.c.texi
2774 @end smallexample
2775
2776 Keep in mind that datagram socket communications are unreliable.  In
2777 this example, the client program waits indefinitely if the message
2778 never reaches the server or if the server's response never comes
2779 back.  It's up to the user running the program to kill and restart
2780 it if desired.  A more automatic solution could be to use
2781 @code{select} (@pxref{Waiting for I/O}) to establish a timeout period
2782 for the reply, and in case of timeout either re-send the message or
2783 shut down the socket and exit.
2784
2785 @node Inetd
2786 @section The @code{inetd} Daemon
2787
2788 We've explained above how to write a server program that does its own
2789 listening.  Such a server must already be running in order for anyone
2790 to connect to it.
2791
2792 Another way to provide a service on an Internet port is to let the daemon
2793 program @code{inetd} do the listening.  @code{inetd} is a program that
2794 runs all the time and waits (using @code{select}) for messages on a
2795 specified set of ports.  When it receives a message, it accepts the
2796 connection (if the socket style calls for connections) and then forks a
2797 child process to run the corresponding server program.  You specify the
2798 ports and their programs in the file @file{/etc/inetd.conf}.
2799
2800 @menu
2801 * Inetd Servers::
2802 * Configuring Inetd::
2803 @end menu
2804
2805 @node Inetd Servers
2806 @subsection @code{inetd} Servers
2807
2808 Writing a server program to be run by @code{inetd} is very simple.  Each time
2809 someone requests a connection to the appropriate port, a new server
2810 process starts.  The connection already exists at this time; the
2811 socket is available as the standard input descriptor and as the
2812 standard output descriptor (descriptors 0 and 1) in the server
2813 process.  Thus the server program can begin reading and writing data
2814 right away.  Often the program needs only the ordinary I/O facilities;
2815 in fact, a general-purpose filter program that knows nothing about
2816 sockets can work as a byte stream server run by @code{inetd}.
2817
2818 You can also use @code{inetd} for servers that use connectionless
2819 communication styles.  For these servers, @code{inetd} does not try to accept
2820 a connection since no connection is possible.  It just starts the
2821 server program, which can read the incoming datagram packet from
2822 descriptor 0.  The server program can handle one request and then
2823 exit, or you can choose to write it to keep reading more requests
2824 until no more arrive, and then exit.  You must specify which of these
2825 two techniques the server uses when you configure @code{inetd}.
2826
2827 @node Configuring Inetd
2828 @subsection Configuring @code{inetd}
2829
2830 The file @file{/etc/inetd.conf} tells @code{inetd} which ports to listen to
2831 and what server programs to run for them.  Normally each entry in the
2832 file is one line, but you can split it onto multiple lines provided
2833 all but the first line of the entry start with whitespace.  Lines that
2834 start with @samp{#} are comments.
2835
2836 Here are two standard entries in @file{/etc/inetd.conf}:
2837
2838 @smallexample
2839 ftp     stream  tcp     nowait  root    /libexec/ftpd   ftpd
2840 talk    dgram   udp     wait    root    /libexec/talkd  talkd
2841 @end smallexample
2842
2843 An entry has this format:
2844
2845 @smallexample
2846 @var{service} @var{style} @var{protocol} @var{wait} @var{username} @var{program} @var{arguments}
2847 @end smallexample
2848
2849 The @var{service} field says which service this program provides.  It
2850 should be the name of a service defined in @file{/etc/services}.
2851 @code{inetd} uses @var{service} to decide which port to listen on for
2852 this entry.
2853
2854 The fields @var{style} and @var{protocol} specify the communication
2855 style and the protocol to use for the listening socket.  The style
2856 should be the name of a communication style, converted to lower case
2857 and with @samp{SOCK_} deleted---for example, @samp{stream} or
2858 @samp{dgram}.  @var{protocol} should be one of the protocols listed in
2859 @file{/etc/protocols}.  The typical protocol names are @samp{tcp} for
2860 byte stream connections and @samp{udp} for unreliable datagrams.
2861
2862 The @var{wait} field should be either @samp{wait} or @samp{nowait}.
2863 Use @samp{wait} if @var{style} is a connectionless style and the
2864 server, once started, handles multiple requests as they come in.
2865 Use @samp{nowait} if @code{inetd} should start a new process for each message
2866 or request that comes in.  If @var{style} uses connections, then
2867 @var{wait} @strong{must} be @samp{nowait}.
2868
2869 @var{user} is the user name that the server should run as.  @code{inetd} runs
2870 as root, so it can set the user ID of its children arbitrarily.  It's
2871 best to avoid using @samp{root} for @var{user} if you can; but some
2872 servers, such as Telnet and FTP, read a username and password
2873 themselves.  These servers need to be root initially so they can log
2874 in as commanded by the data coming over the network.
2875
2876 @var{program} together with @var{arguments} specifies the command to
2877 run to start the server.  @var{program} should be an absolute file
2878 name specifying the executable file to run.  @var{arguments} consists
2879 of any number of whitespace-separated words, which become the
2880 command-line arguments of @var{program}.  The first word in
2881 @var{arguments} is argument zero, which should by convention be the
2882 program name itself (sans directories).
2883
2884 If you edit @file{/etc/inetd.conf}, you can tell @code{inetd} to reread the
2885 file and obey its new contents by sending the @code{inetd} process the
2886 @code{SIGHUP} signal.  You'll have to use @code{ps} to determine the
2887 process ID of the @code{inetd} process as it is not fixed.
2888
2889 @c !!! could document /etc/inetd.sec
2890
2891 @node Socket Options
2892 @section Socket Options
2893 @cindex socket options
2894
2895 This section describes how to read or set various options that modify
2896 the behavior of sockets and their underlying communications protocols.
2897
2898 @cindex level, for socket options
2899 @cindex socket option level
2900 When you are manipulating a socket option, you must specify which
2901 @dfn{level} the option pertains to.  This describes whether the option
2902 applies to the socket interface, or to a lower-level communications
2903 protocol interface.
2904
2905 @menu
2906 * Socket Option Functions::     The basic functions for setting and getting
2907                                  socket options.
2908 * Socket-Level Options::        Details of the options at the socket level.
2909 @end menu
2910
2911 @node Socket Option Functions
2912 @subsection Socket Option Functions
2913
2914 @pindex sys/socket.h
2915 Here are the functions for examining and modifying socket options.
2916 They are declared in @file{sys/socket.h}.
2917
2918 @comment sys/socket.h
2919 @comment BSD
2920 @deftypefun int getsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t *@var{optlen-ptr})
2921 The @code{getsockopt} function gets information about the value of
2922 option @var{optname} at level @var{level} for socket @var{socket}.
2923
2924 The option value is stored in a buffer that @var{optval} points to.
2925 Before the call, you should supply in @code{*@var{optlen-ptr}} the
2926 size of this buffer; on return, it contains the number of bytes of
2927 information actually stored in the buffer.
2928
2929 Most options interpret the @var{optval} buffer as a single @code{int}
2930 value.
2931
2932 The actual return value of @code{getsockopt} is @code{0} on success
2933 and @code{-1} on failure.  The following @code{errno} error conditions
2934 are defined:
2935
2936 @table @code
2937 @item EBADF
2938 The @var{socket} argument is not a valid file descriptor.
2939
2940 @item ENOTSOCK
2941 The descriptor @var{socket} is not a socket.
2942
2943 @item ENOPROTOOPT
2944 The @var{optname} doesn't make sense for the given @var{level}.
2945 @end table
2946 @end deftypefun
2947
2948 @comment sys/socket.h
2949 @comment BSD
2950 @deftypefun int setsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t @var{optlen})
2951 This function is used to set the socket option @var{optname} at level
2952 @var{level} for socket @var{socket}.  The value of the option is passed
2953 in the buffer @var{optval} of size @var{optlen}.
2954
2955 @c Argh. -zw
2956 @iftex
2957 @hfuzz 6pt
2958 The return value and error codes for @code{setsockopt} are the same as
2959 for @code{getsockopt}.
2960 @end iftex
2961 @ifinfo
2962 The return value and error codes for @code{setsockopt} are the same as
2963 for @code{getsockopt}.
2964 @end ifinfo
2965
2966 @end deftypefun
2967
2968 @node Socket-Level Options
2969 @subsection Socket-Level Options
2970
2971 @comment sys/socket.h
2972 @comment BSD
2973 @deftypevr Constant int SOL_SOCKET
2974 Use this constant as the @var{level} argument to @code{getsockopt} or
2975 @code{setsockopt} to manipulate the socket-level options described in
2976 this section.
2977 @end deftypevr
2978
2979 @pindex sys/socket.h
2980 @noindent
2981 Here is a table of socket-level option names; all are defined in the
2982 header file @file{sys/socket.h}.
2983
2984 @table @code
2985 @comment sys/socket.h
2986 @comment BSD
2987 @item SO_DEBUG
2988 @c Extra blank line here makes the table look better.
2989
2990 This option toggles recording of debugging information in the underlying
2991 protocol modules.  The value has type @code{int}; a nonzero value means
2992 ``yes''.
2993 @c !!! should say how this is used
2994 @c OK, anyone who knows, please explain.
2995
2996 @comment sys/socket.h
2997 @comment BSD
2998 @item SO_REUSEADDR
2999 This option controls whether @code{bind} (@pxref{Setting Address})
3000 should permit reuse of local addresses for this socket.  If you enable
3001 this option, you can actually have two sockets with the same Internet
3002 port number; but the system won't allow you to use the two
3003 identically-named sockets in a way that would confuse the Internet.  The
3004 reason for this option is that some higher-level Internet protocols,
3005 including FTP, require you to keep reusing the same port number.
3006
3007 The value has type @code{int}; a nonzero value means ``yes''.
3008
3009 @comment sys/socket.h
3010 @comment BSD
3011 @item SO_KEEPALIVE
3012 This option controls whether the underlying protocol should
3013 periodically transmit messages on a connected socket.  If the peer
3014 fails to respond to these messages, the connection is considered
3015 broken.  The value has type @code{int}; a nonzero value means
3016 ``yes''.
3017
3018 @comment sys/socket.h
3019 @comment BSD
3020 @item SO_DONTROUTE
3021 This option controls whether outgoing messages bypass the normal
3022 message routing facilities.  If set, messages are sent directly to the
3023 network interface instead.  The value has type @code{int}; a nonzero
3024 value means ``yes''.
3025
3026 @comment sys/socket.h
3027 @comment BSD
3028 @item SO_LINGER
3029 This option specifies what should happen when the socket of a type
3030 that promises reliable delivery still has untransmitted messages when
3031 it is closed; see @ref{Closing a Socket}.  The value has type
3032 @code{struct linger}.
3033
3034 @comment sys/socket.h
3035 @comment BSD
3036 @deftp {Data Type} {struct linger}
3037 This structure type has the following members:
3038
3039 @table @code
3040 @item int l_onoff
3041 This field is interpreted as a boolean.  If nonzero, @code{close}
3042 blocks until the data are transmitted or the timeout period has expired.
3043
3044 @item int l_linger
3045 This specifies the timeout period, in seconds.
3046 @end table
3047 @end deftp
3048
3049 @comment sys/socket.h
3050 @comment BSD
3051 @item SO_BROADCAST
3052 This option controls whether datagrams may be broadcast from the socket.
3053 The value has type @code{int}; a nonzero value means ``yes''.
3054
3055 @comment sys/socket.h
3056 @comment BSD
3057 @item SO_OOBINLINE
3058 If this option is set, out-of-band data received on the socket is
3059 placed in the normal input queue.  This permits it to be read using
3060 @code{read} or @code{recv} without specifying the @code{MSG_OOB}
3061 flag.  @xref{Out-of-Band Data}.  The value has type @code{int}; a
3062 nonzero value means ``yes''.
3063
3064 @comment sys/socket.h
3065 @comment BSD
3066 @item SO_SNDBUF
3067 This option gets or sets the size of the output buffer.  The value is a
3068 @code{size_t}, which is the size in bytes.
3069
3070 @comment sys/socket.h
3071 @comment BSD
3072 @item SO_RCVBUF
3073 This option gets or sets the size of the input buffer.  The value is a
3074 @code{size_t}, which is the size in bytes.
3075
3076 @comment sys/socket.h
3077 @comment GNU
3078 @item SO_STYLE
3079 @comment sys/socket.h
3080 @comment BSD
3081 @itemx SO_TYPE
3082 This option can be used with @code{getsockopt} only.  It is used to
3083 get the socket's communication style.  @code{SO_TYPE} is the
3084 historical name, and @code{SO_STYLE} is the preferred name in GNU.
3085 The value has type @code{int} and its value designates a communication
3086 style; see @ref{Communication Styles}.
3087
3088 @comment sys/socket.h
3089 @comment BSD
3090 @item SO_ERROR
3091 @c Extra blank line here makes the table look better.
3092
3093 This option can be used with @code{getsockopt} only.  It is used to reset
3094 the error status of the socket.  The value is an @code{int}, which represents
3095 the previous error status.
3096 @c !!! what is "socket error status"?  this is never defined.
3097 @end table
3098
3099 @node Networks Database
3100 @section Networks Database
3101 @cindex networks database
3102 @cindex converting network number to network name
3103 @cindex converting network name to network number
3104
3105 @pindex /etc/networks
3106 @pindex netdb.h
3107 Many systems come with a database that records a list of networks known
3108 to the system developer.  This is usually kept either in the file
3109 @file{/etc/networks} or in an equivalent from a name server.  This data
3110 base is useful for routing programs such as @code{route}, but it is not
3111 useful for programs that simply communicate over the network.  We
3112 provide functions to access this database, which are declared in
3113 @file{netdb.h}.
3114
3115 @comment netdb.h
3116 @comment BSD
3117 @deftp {Data Type} {struct netent}
3118 This data type is used to represent information about entries in the
3119 networks database.  It has the following members:
3120
3121 @table @code
3122 @item char *n_name
3123 This is the ``official'' name of the network.
3124
3125 @item char **n_aliases
3126 These are alternative names for the network, represented as a vector
3127 of strings.  A null pointer terminates the array.
3128
3129 @item int n_addrtype
3130 This is the type of the network number; this is always equal to
3131 @code{AF_INET} for Internet networks.
3132
3133 @item unsigned long int n_net
3134 This is the network number.  Network numbers are returned in host
3135 byte order; see @ref{Byte Order}.
3136 @end table
3137 @end deftp
3138
3139 Use the @code{getnetbyname} or @code{getnetbyaddr} functions to search
3140 the networks database for information about a specific network.  The
3141 information is returned in a statically-allocated structure; you must
3142 copy the information if you need to save it.
3143
3144 @comment netdb.h
3145 @comment BSD
3146 @deftypefun {struct netent *} getnetbyname (const char *@var{name})
3147 The @code{getnetbyname} function returns information about the network
3148 named @var{name}.  It returns a null pointer if there is no such
3149 network.
3150 @end deftypefun
3151
3152 @comment netdb.h
3153 @comment BSD
3154 @deftypefun {struct netent *} getnetbyaddr (unsigned long int @var{net}, int @var{type})
3155 The @code{getnetbyaddr} function returns information about the network
3156 of type @var{type} with number @var{net}.  You should specify a value of
3157 @code{AF_INET} for the @var{type} argument for Internet networks.
3158
3159 @code{getnetbyaddr} returns a null pointer if there is no such
3160 network.
3161 @end deftypefun
3162
3163 You can also scan the networks database using @code{setnetent},
3164 @code{getnetent} and @code{endnetent}.  Be careful when using these
3165 functions because they are not reentrant.
3166
3167 @comment netdb.h
3168 @comment BSD
3169 @deftypefun void setnetent (int @var{stayopen})
3170 This function opens and rewinds the networks database.
3171
3172 If the @var{stayopen} argument is nonzero, this sets a flag so that
3173 subsequent calls to @code{getnetbyname} or @code{getnetbyaddr} will
3174 not close the database (as they usually would).  This makes for more
3175 efficiency if you call those functions several times, by avoiding
3176 reopening the database for each call.
3177 @end deftypefun
3178
3179 @comment netdb.h
3180 @comment BSD
3181 @deftypefun {struct netent *} getnetent (void)
3182 This function returns the next entry in the networks database.  It
3183 returns a null pointer if there are no more entries.
3184 @end deftypefun
3185
3186 @comment netdb.h
3187 @comment BSD
3188 @deftypefun void endnetent (void)
3189 This function closes the networks database.
3190 @end deftypefun