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