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