Update.
[glibc.git] / manual / socket.texi
blob9cb9b435e401b688e4d28265ddc699fbfaacc29d
1 @node Sockets, Low-Level Terminal Interface, Pipes and FIFOs, Top
2 @chapter Sockets
4 This chapter describes the GNU facilities for interprocess
5 communication using sockets.
7 @cindex socket
8 @cindex interprocess communication, with sockets
9 A @dfn{socket} is a generalized interprocess communication channel.
10 Like a pipe, a socket is represented as a file descriptor.  But,
11 unlike pipes, sockets support communication between unrelated
12 processes, and even between processes running on different machines
13 that communicate over a network.  Sockets are the primary means of
14 communicating with other machines; @code{telnet}, @code{rlogin},
15 @code{ftp}, @code{talk}, and the other familiar network programs use
16 sockets.
18 Not all operating systems support sockets.  In the GNU library, the
19 header file @file{sys/socket.h} exists regardless of the operating
20 system, and the socket functions always exist, but if the system does
21 not really support sockets, these functions always fail.
23 @strong{Incomplete:} We do not currently document the facilities for
24 broadcast messages or for configuring Internet interfaces.
26 @menu
27 * Socket Concepts::     Basic concepts you need to know about.
28 * Communication Styles::Stream communication, datagrams, and other styles.
29 * Socket Addresses::    How socket names (``addresses'') work.
30 * File Namespace::      Details about the file namespace.
31 * Internet Namespace::  Details about the Internet namespace.
32 * Misc Namespaces::     Other namespaces not documented fully here.
33 * Open/Close Sockets::  Creating sockets and destroying them.
34 * Connections::         Operations on sockets with connection state.
35 * Datagrams::           Operations on datagram sockets.
36 * Inetd::               Inetd is a daemon that starts servers on request.
37                            The most convenient way to write a server
38                            is to make it work with Inetd.
39 * Socket Options::      Miscellaneous low-level socket options.
40 * Networks Database::   Accessing the database of network names.
41 @end menu
43 @node Socket Concepts
44 @section Socket Concepts
46 @cindex communication style (of a socket)
47 @cindex style of communication (of a socket)
48 When you create a socket, you must specify the style of communication
49 you want to use and the type of protocol that should implement it.
50 The @dfn{communication style} of a socket defines the user-level
51 semantics of sending and receiving data on the socket.  Choosing a
52 communication style specifies the answers to questions such as these:
54 @itemize @bullet
55 @item
56 @cindex packet
57 @cindex byte stream
58 @cindex stream (sockets)
59 @strong{What are the units of data transmission?}  Some communication
60 styles regard the data as a sequence of bytes, with no larger
61 structure; others group the bytes into records (which are known in
62 this context as @dfn{packets}).
64 @item
65 @cindex loss of data on sockets
66 @cindex data loss on sockets
67 @strong{Can data be lost during normal operation?}  Some communication
68 styles guarantee that all the data sent arrives in the order it was
69 sent (barring system or network crashes); other styles occasionally
70 lose data as a normal part of operation, and may sometimes deliver
71 packets more than once or in the wrong order.
73 Designing a program to use unreliable communication styles usually
74 involves taking precautions to detect lost or misordered packets and
75 to retransmit data as needed.
77 @item
78 @strong{Is communication entirely with one partner?}  Some
79 communication styles are like a telephone call---you make a
80 @dfn{connection} with one remote socket, and then exchange data
81 freely.  Other styles are like mailing letters---you specify a
82 destination address for each message you send.
83 @end itemize
85 @cindex namespace (of socket)
86 @cindex domain (of socket)
87 @cindex socket namespace
88 @cindex socket domain
89 You must also choose a @dfn{namespace} for naming the socket.  A socket
90 name (``address'') is meaningful only in the context of a particular
91 namespace.  In fact, even the data type to use for a socket name may
92 depend on the namespace.  Namespaces are also called ``domains'', but we
93 avoid that word as it can be confused with other usage of the same
94 term.  Each namespace has a symbolic name that starts with @samp{PF_}.
95 A corresponding symbolic name starting with @samp{AF_} designates the
96 address format for that namespace.
98 @cindex network protocol
99 @cindex protocol (of socket)
100 @cindex socket protocol
101 @cindex protocol family
102 Finally you must choose the @dfn{protocol} to carry out the
103 communication.  The protocol determines what low-level mechanism is used
104 to transmit and receive data.  Each protocol is valid for a particular
105 namespace and communication style; a namespace is sometimes called a
106 @dfn{protocol family} because of this, which is why the namespace names
107 start with @samp{PF_}.
109 The rules of a protocol apply to the data passing between two programs,
110 perhaps on different computers; most of these rules are handled by the
111 operating system, and you need not know about them.  What you do need to
112 know about protocols is this:
114 @itemize @bullet
115 @item
116 In order to have communication between two sockets, they must specify
117 the @emph{same} protocol.
119 @item
120 Each protocol is meaningful with particular style/namespace
121 combinations and cannot be used with inappropriate combinations.  For
122 example, the TCP protocol fits only the byte stream style of
123 communication and the Internet namespace.
125 @item
126 For each combination of style and namespace, there is a @dfn{default
127 protocol} which you can request by specifying 0 as the protocol
128 number.  And that's what you should normally do---use the default.
129 @end itemize
131 Throughout the following description at various places
132 variables/parameters to denote sizes are required.  And here the trouble
133 starts.  In the first implementations the type of these variables was
134 simply @code{int}.  This type was on almost all machines of this time 32
135 bits wide and so a de-factor standard required 32 bit variables.  This
136 is important since references to variables of this type are passed to
137 the kernel.
139 But now the POSIX people came and unified the interface with their words
140 "all size values are of type @code{size_t}".  But on 64 bit machines
141 @code{size_t} is 64 bits wide and so variable references are not anymore
142 possible.
144 A solution provides the Unix98 specification which finally introduces a
145 type @code{socklen_t}.  This type is used in all of the cases that were
146 previously changed to use @code{size_t}.  The only requirement of this
147 type is that it is an unsigned type of at least 32 bits.  Therefore,
148 implementations which require references to 32 bit variables be passed
149 can be as happy as implementations which use right from the start 64 bit
150 values.
153 @node Communication Styles
154 @section Communication Styles
156 The GNU library includes support for several different kinds of sockets,
157 each with different characteristics.  This section describes the
158 supported socket types.  The symbolic constants listed here are
159 defined in @file{sys/socket.h}.
160 @pindex sys/socket.h
162 @comment sys/socket.h
163 @comment BSD
164 @deftypevr Macro int SOCK_STREAM
165 The @code{SOCK_STREAM} style is like a pipe (@pxref{Pipes and FIFOs});
166 it operates over a connection with a particular remote socket, and
167 transmits data reliably as a stream of bytes.
169 Use of this style is covered in detail in @ref{Connections}.
170 @end deftypevr
172 @comment sys/socket.h
173 @comment BSD
174 @deftypevr Macro int SOCK_DGRAM
175 The @code{SOCK_DGRAM} style is used for sending
176 individually-addressed packets, unreliably.
177 It is the diametrical opposite of @code{SOCK_STREAM}.
179 Each time you write data to a socket of this kind, that data becomes
180 one packet.  Since @code{SOCK_DGRAM} sockets do not have connections,
181 you must specify the recipient address with each packet.
183 The only guarantee that the system makes about your requests to
184 transmit data is that it will try its best to deliver each packet you
185 send.  It may succeed with the sixth packet after failing with the
186 fourth and fifth packets; the seventh packet may arrive before the
187 sixth, and may arrive a second time after the sixth.
189 The typical use for @code{SOCK_DGRAM} is in situations where it is
190 acceptable to simply resend a packet if no response is seen in a
191 reasonable amount of time.
193 @xref{Datagrams}, for detailed information about how to use datagram
194 sockets.
195 @end deftypevr
197 @ignore
198 @c This appears to be only for the NS domain, which we aren't
199 @c discussing and probably won't support either.
200 @comment sys/socket.h
201 @comment BSD
202 @deftypevr Macro int SOCK_SEQPACKET
203 This style is like @code{SOCK_STREAM} except that the data is
204 structured into packets.
206 A program that receives data over a @code{SOCK_SEQPACKET} socket
207 should be prepared to read the entire message packet in a single call
208 to @code{read}; if it only reads part of the message, the remainder of
209 the message is simply discarded instead of being available for
210 subsequent calls to @code{read}.
212 Many protocols do not support this communication style.
213 @end deftypevr
214 @end ignore
216 @ignore
217 @comment sys/socket.h
218 @comment BSD
219 @deftypevr Macro int SOCK_RDM
220 This style is a reliable version of @code{SOCK_DGRAM}: it sends
221 individually addressed packets, but guarantees that each packet sent
222 arrives exactly once.
224 @strong{Warning:} It is not clear this is actually supported
225 by any operating system.
226 @end deftypevr
227 @end ignore
229 @comment sys/socket.h
230 @comment BSD
231 @deftypevr Macro int SOCK_RAW
232 This style provides access to low-level network protocols and
233 interfaces.  Ordinary user programs usually have no need to use this
234 style.
235 @end deftypevr
237 @node Socket Addresses
238 @section Socket Addresses
240 @cindex address of socket
241 @cindex name of socket
242 @cindex binding a socket address
243 @cindex socket address (name) binding
244 The name of a socket is normally called an @dfn{address}.  The
245 functions and symbols for dealing with socket addresses were named
246 inconsistently, sometimes using the term ``name'' and sometimes using
247 ``address''.  You can regard these terms as synonymous where sockets
248 are concerned.
250 A socket newly created with the @code{socket} function has no
251 address.  Other processes can find it for communication only if you
252 give it an address.  We call this @dfn{binding} the address to the
253 socket, and the way to do it is with the @code{bind} function.
255 You need be concerned with the address of a socket if other processes
256 are to find it and start communicating with it.  You can specify an
257 address for other sockets, but this is usually pointless; the first time
258 you send data from a socket, or use it to initiate a connection, the
259 system assigns an address automatically if you have not specified one.
261 Occasionally a client needs to specify an address because the server
262 discriminates based on addresses; for example, the rsh and rlogin
263 protocols look at the client's socket address and don't bypass password
264 checking unless it is less than @code{IPPORT_RESERVED} (@pxref{Ports}).
266 The details of socket addresses vary depending on what namespace you are
267 using.  @xref{File Namespace}, or @ref{Internet Namespace}, for specific
268 information.
270 Regardless of the namespace, you use the same functions @code{bind} and
271 @code{getsockname} to set and examine a socket's address.  These
272 functions use a phony data type, @code{struct sockaddr *}, to accept the
273 address.  In practice, the address lives in a structure of some other
274 data type appropriate to the address format you are using, but you cast
275 its address to @code{struct sockaddr *} when you pass it to
276 @code{bind}.
278 @menu
279 * Address Formats::             About @code{struct sockaddr}.
280 * Setting Address::             Binding an address to a socket.
281 * Reading Address::             Reading the address of a socket.
282 @end menu
284 @node Address Formats
285 @subsection Address Formats
287 The functions @code{bind} and @code{getsockname} use the generic data
288 type @code{struct sockaddr *} to represent a pointer to a socket
289 address.  You can't use this data type effectively to interpret an
290 address or construct one; for that, you must use the proper data type
291 for the socket's namespace.
293 Thus, the usual practice is to construct an address in the proper
294 namespace-specific type, then cast a pointer to @code{struct sockaddr *}
295 when you call @code{bind} or @code{getsockname}.
297 The one piece of information that you can get from the @code{struct
298 sockaddr} data type is the @dfn{address format} designator which tells
299 you which data type to use to understand the address fully.
301 @pindex sys/socket.h
302 The symbols in this section are defined in the header file
303 @file{sys/socket.h}.
305 @comment sys/socket.h
306 @comment BSD
307 @deftp {Date Type} {struct sockaddr}
308 The @code{struct sockaddr} type itself has the following members:
310 @table @code
311 @item short int sa_family
312 This is the code for the address format of this address.  It
313 identifies the format of the data which follows.
315 @item char sa_data[14]
316 This is the actual socket address data, which is format-dependent.  Its
317 length also depends on the format, and may well be more than 14.  The
318 length 14 of @code{sa_data} is essentially arbitrary.
319 @end table
320 @end deftp
322 Each address format has a symbolic name which starts with @samp{AF_}.
323 Each of them corresponds to a @samp{PF_} symbol which designates the
324 corresponding namespace.  Here is a list of address format names:
326 @table @code
327 @comment sys/socket.h
328 @comment GNU
329 @item AF_FILE
330 @vindex AF_FILE
331 This designates the address format that goes with the file namespace.
332 (@code{PF_FILE} is the name of that namespace.)  @xref{File Namespace
333 Details}, for information about this address format.
335 @comment sys/socket.h
336 @comment BSD
337 @item AF_UNIX
338 @vindex AF_UNIX
339 This is a synonym for @code{AF_FILE}, for compatibility.
340 (@code{PF_UNIX} is likewise a synonym for @code{PF_FILE}.)
342 @comment sys/socket.h
343 @comment BSD
344 @item AF_INET
345 @vindex AF_INET
346 This designates the address format that goes with the Internet
347 namespace.  (@code{PF_INET} is the name of that namespace.)
348 @xref{Internet Address Formats}.
350 @comment sys/socket.h
351 @comment IPv6 Basic API
352 @item AF_INET6
353 This is similar to @code{AF_INET}, but refers to the IPv6 protocol.
354 (@code{PF_INET6} is the name of the corresponding namespace.)
356 @comment sys/socket.h
357 @comment BSD
358 @item AF_UNSPEC
359 @vindex AF_UNSPEC
360 This designates no particular address format.  It is used only in rare
361 cases, such as to clear out the default destination address of a
362 ``connected'' datagram socket.  @xref{Sending Datagrams}.
364 The corresponding namespace designator symbol @code{PF_UNSPEC} exists
365 for completeness, but there is no reason to use it in a program.
366 @end table
368 @file{sys/socket.h} defines symbols starting with @samp{AF_} for many
369 different kinds of networks, all or most of which are not actually
370 implemented.  We will document those that really work, as we receive
371 information about how to use them.
373 @node Setting Address
374 @subsection Setting the Address of a Socket
376 @pindex sys/socket.h
377 Use the @code{bind} function to assign an address to a socket.  The
378 prototype for @code{bind} is in the header file @file{sys/socket.h}.
379 For examples of use, see @ref{File Namespace}, or see @ref{Inet Example}.
381 @comment sys/socket.h
382 @comment BSD
383 @deftypefun int bind (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
384 The @code{bind} function assigns an address to the socket
385 @var{socket}.  The @var{addr} and @var{length} arguments specify the
386 address; the detailed format of the address depends on the namespace.
387 The first part of the address is always the format designator, which
388 specifies a namespace, and says that the address is in the format for
389 that namespace.
391 The return value is @code{0} on success and @code{-1} on failure.  The
392 following @code{errno} error conditions are defined for this function:
394 @table @code
395 @item EBADF
396 The @var{socket} argument is not a valid file descriptor.
398 @item ENOTSOCK
399 The descriptor @var{socket} is not a socket.
401 @item EADDRNOTAVAIL
402 The specified address is not available on this machine.
404 @item EADDRINUSE
405 Some other socket is already using the specified address.
407 @item EINVAL
408 The socket @var{socket} already has an address.
410 @item EACCES
411 You do not have permission to access the requested address.  (In the
412 Internet domain, only the super-user is allowed to specify a port number
413 in the range 0 through @code{IPPORT_RESERVED} minus one; see
414 @ref{Ports}.)
415 @end table
417 Additional conditions may be possible depending on the particular namespace
418 of the socket.
419 @end deftypefun
421 @node Reading Address
422 @subsection Reading the Address of a Socket
424 @pindex sys/socket.h
425 Use the function @code{getsockname} to examine the address of an
426 Internet socket.  The prototype for this function is in the header file
427 @file{sys/socket.h}.
429 @comment sys/socket.h
430 @comment BSD
431 @deftypefun int getsockname (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
432 The @code{getsockname} function returns information about the
433 address of the socket @var{socket} in the locations specified by the
434 @var{addr} and @var{length-ptr} arguments.  Note that the
435 @var{length-ptr} is a pointer; you should initialize it to be the
436 allocation size of @var{addr}, and on return it contains the actual
437 size of the address data.
439 The format of the address data depends on the socket namespace.  The
440 length of the information is usually fixed for a given namespace, so
441 normally you can know exactly how much space is needed and can provide
442 that much.  The usual practice is to allocate a place for the value
443 using the proper data type for the socket's namespace, then cast its
444 address to @code{struct sockaddr *} to pass it to @code{getsockname}.
446 The return value is @code{0} on success and @code{-1} on error.  The
447 following @code{errno} error conditions are defined for this function:
449 @table @code
450 @item EBADF
451 The @var{socket} argument is not a valid file descriptor.
453 @item ENOTSOCK
454 The descriptor @var{socket} is not a socket.
456 @item ENOBUFS
457 There are not enough internal buffers available for the operation.
458 @end table
459 @end deftypefun
461 You can't read the address of a socket in the file namespace.  This is
462 consistent with the rest of the system; in general, there's no way to
463 find a file's name from a descriptor for that file.
465 @node File Namespace
466 @section The File Namespace
467 @cindex file namespace, for sockets
469 This section describes the details of the file namespace, whose
470 symbolic name (required when you create a socket) is @code{PF_FILE}.
472 @menu
473 * Concepts: File Namespace Concepts.    What you need to understand.
474 * Details: File Namespace Details.      Address format, symbolic names, etc.
475 * Example: File Socket Example.         Example of creating a socket.
476 @end menu
478 @node File Namespace Concepts
479 @subsection File Namespace Concepts
481 In the file namespace, socket addresses are file names.  You can specify
482 any file name you want as the address of the socket, but you must have
483 write permission on the directory containing it.  In order to connect to
484 a socket, you must have read permission for it.  It's common to put
485 these files in the @file{/tmp} directory.
487 One peculiarity of the file namespace is that the name is only used when
488 opening the connection; once that is over with, the address is not
489 meaningful and may not exist.
491 Another peculiarity is that you cannot connect to such a socket from
492 another machine--not even if the other machine shares the file system
493 which contains the name of the socket.  You can see the socket in a
494 directory listing, but connecting to it never succeeds.  Some programs
495 take advantage of this, such as by asking the client to send its own
496 process ID, and using the process IDs to distinguish between clients.
497 However, we recommend you not use this method in protocols you design,
498 as we might someday permit connections from other machines that mount
499 the same file systems.  Instead, send each new client an identifying
500 number if you want it to have one.
502 After you close a socket in the file namespace, you should delete the
503 file name from the file system.  Use @code{unlink} or @code{remove} to
504 do this; see @ref{Deleting Files}.
506 The file namespace supports just one protocol for any communication
507 style; it is protocol number @code{0}.
509 @node File Namespace Details
510 @subsection Details of File Namespace
512 @pindex sys/socket.h
513 To create a socket in the file namespace, use the constant
514 @code{PF_FILE} as the @var{namespace} argument to @code{socket} or
515 @code{socketpair}.  This constant is defined in @file{sys/socket.h}.
517 @comment sys/socket.h
518 @comment GNU
519 @deftypevr Macro int PF_FILE
520 This designates the file namespace, in which socket addresses are file
521 names, and its associated family of protocols.
522 @end deftypevr
524 @comment sys/socket.h
525 @comment BSD
526 @deftypevr Macro int PF_UNIX
527 This is a synonym for @code{PF_FILE}, for compatibility's sake.
528 @end deftypevr
530 The structure for specifying socket names in the file namespace is
531 defined in the header file @file{sys/un.h}:
532 @pindex sys/un.h
534 @comment sys/un.h
535 @comment BSD
536 @deftp {Data Type} {struct sockaddr_un}
537 This structure is used to specify file namespace socket addresses.  It has
538 the following members:
540 @table @code
541 @item short int sun_family
542 This identifies the address family or format of the socket address.
543 You should store the value @code{AF_FILE} to designate the file
544 namespace.  @xref{Socket Addresses}.
546 @item char sun_path[108]
547 This is the file name to use.
549 @strong{Incomplete:}  Why is 108 a magic number?  RMS suggests making
550 this a zero-length array and tweaking the example following to use
551 @code{alloca} to allocate an appropriate amount of storage based on
552 the length of the filename.
553 @end table
554 @end deftp
556 You should compute the @var{length} parameter for a socket address in
557 the file namespace as the sum of the size of the @code{sun_family}
558 component and the string length (@emph{not} the allocation size!) of
559 the file name string.
561 @node File Socket Example
562 @subsection Example of File-Namespace Sockets
564 Here is an example showing how to create and name a socket in the file
565 namespace.
567 @smallexample
568 @include mkfsock.c.texi
569 @end smallexample
571 @node Internet Namespace
572 @section The Internet Namespace
573 @cindex Internet namespace, for sockets
575 This section describes the details the protocols and socket naming
576 conventions used in the Internet namespace.
578 To create a socket in the Internet namespace, use the symbolic name
579 @code{PF_INET} of this namespace as the @var{namespace} argument to
580 @code{socket} or @code{socketpair}.  This macro is defined in
581 @file{sys/socket.h}.
582 @pindex sys/socket.h
584 @comment sys/socket.h
585 @comment BSD
586 @deftypevr Macro int PF_INET
587 This designates the Internet namespace and associated family of
588 protocols.
589 @end deftypevr
591 A socket address for the Internet namespace includes the following components:
593 @itemize @bullet
594 @item
595 The address of the machine you want to connect to.  Internet addresses
596 can be specified in several ways; these are discussed in @ref{Internet
597 Address Formats}, @ref{Host Addresses}, and @ref{Host Names}.
599 @item
600 A port number for that machine.  @xref{Ports}.
601 @end itemize
603 You must ensure that the address and port number are represented in a
604 canonical format called @dfn{network byte order}.  @xref{Byte Order},
605 for information about this.
607 @menu
608 * Internet Address Formats::    How socket addresses are specified in the
609                                  Internet namespace.
610 * Host Addresses::              All about host addresses of internet host.
611 * Protocols Database::          Referring to protocols by name.
612 * Ports::                       Internet port numbers.
613 * Services Database::           Ports may have symbolic names.
614 * Byte Order::                  Different hosts may use different byte
615                                  ordering conventions; you need to
616                                  canonicalize host address and port number.
617 * Inet Example::                Putting it all together.
618 @end menu
620 @node Internet Address Formats
621 @subsection Internet Socket Address Formats
623 In the Internet namespace, for both IPv4 (@code{AF_INET}) and IPv6
624 (@code{AF_INET6}), a socket address consists of a host address
625 and a port on that host.  In addition, the protocol you choose serves
626 effectively as a part of the address because local port numbers are
627 meaningful only within a particular protocol.
629 The data types for representing socket addresses in the Internet namespace
630 are defined in the header file @file{netinet/in.h}.
631 @pindex netinet/in.h
633 @comment netinet/in.h
634 @comment BSD
635 @deftp {Data Type} {struct sockaddr_in}
636 This is the data type used to represent socket addresses in the
637 Internet namespace.  It has the following members:
639 @table @code
640 @item short int sin_family
641 This identifies the address family or format of the socket address.
642 You should store the value of @code{AF_INET} in this member.
643 @xref{Socket Addresses}.
645 @item struct in_addr sin_addr
646 This is the Internet address of the host machine.  @xref{Host
647 Addresses}, and @ref{Host Names}, for how to get a value to store
648 here.
650 @item unsigned short int sin_port
651 This is the port number.  @xref{Ports}.
652 @end table
653 @end deftp
655 When you call @code{bind} or @code{getsockname}, you should specify
656 @code{sizeof (struct sockaddr_in)} as the @var{length} parameter if
657 you are using an Internet namespace socket address.
659 @deftp {Data Type} {struct sockaddr_in6}
660 This is the data type used to represent socket addresses in the IPv6
661 namespace.  It has the following members:
663 @table @code
664 @item short int sin6_family
665 This identifies the address family or format of the socket address.
666 You should store the value of @code{AF_INET6} in this member.
667 @xref{Socket Addresses}.
669 @item struct in6_addr sin6_addr
670 This is the IPv6 address of the host machine.  @xref{Host
671 Addresses}, and @ref{Host Names}, for how to get a value to store
672 here.
674 @item uint32_t sin6_flowinfo
675 This is a currently unimplemented field.
677 @item uint16_t sin6_port
678 This is the port number.  @xref{Ports}.
680 @end table
681 @end deftp
683 @node Host Addresses
684 @subsection Host Addresses
686 Each computer on the Internet has one or more @dfn{Internet addresses},
687 numbers which identify that computer among all those on the Internet.
688 Users typically write IPv4 numeric host addresses as sequences of four
689 numbers, separated by periods, as in @samp{128.52.46.32}, and IPv6
690 numeric host addresses as sequences of up to eight numbers seperated by
691 colons, as in @samp{5f03:1200:836f:c100::1}.
693 Each computer also has one or more @dfn{host names}, which are strings
694 of words separated by periods, as in @samp{churchy.gnu.ai.mit.edu}.
696 Programs that let the user specify a host typically accept both numeric
697 addresses and host names.  But the program needs a numeric address to
698 open a connection; to use a host name, you must convert it to the
699 numeric address it stands for.
701 @menu
702 * Abstract Host Addresses::     What a host number consists of.
703 * Data type: Host Address Data Type.    Data type for a host number.
704 * Functions: Host Address Functions.    Functions to operate on them.
705 * Names: Host Names.            Translating host names to host numbers.
706 @end menu
708 @node Abstract Host Addresses
709 @subsubsection Internet Host Addresses
710 @cindex host address, Internet
711 @cindex Internet host address
713 @ifinfo
714 Each computer on the Internet has one or more Internet addresses,
715 numbers which identify that computer among all those on the Internet.
716 @end ifinfo
718 @c I think this whole section could possibly be removed.  It is slightly
719 @c misleading these days.
721 @cindex network number
722 @cindex local network address number
723 An Internet host address is a number containing four bytes of data.
724 These are divided into two parts, a @dfn{network number} and a
725 @dfn{local network address number} within that network.  The network
726 number consists of the first one, two or three bytes; the rest of the
727 bytes are the local address.
729 Network numbers are registered with the Network Information Center
730 (NIC), and are divided into three classes---A, B, and C.  The local
731 network address numbers of individual machines are registered with the
732 administrator of the particular network.
734 Class A networks have single-byte numbers in the range 0 to 127.  There
735 are only a small number of Class A networks, but they can each support a
736 very large number of hosts.  Medium-sized Class B networks have two-byte
737 network numbers, with the first byte in the range 128 to 191.  Class C
738 networks are the smallest; they have three-byte network numbers, with
739 the first byte in the range 192-255.  Thus, the first 1, 2, or 3 bytes
740 of an Internet address specifies a network.  The remaining bytes of the
741 Internet address specify the address within that network.
743 The Class A network 0 is reserved for broadcast to all networks.  In
744 addition, the host number 0 within each network is reserved for broadcast
745 to all hosts in that network.
747 The Class A network 127 is reserved for loopback; you can always use
748 the Internet address @samp{127.0.0.1} to refer to the host machine.
750 Since a single machine can be a member of multiple networks, it can
751 have multiple Internet host addresses.  However, there is never
752 supposed to be more than one machine with the same host address.
754 @c !!! this section could document the IN_CLASS* macros in <netinet/in.h>.
756 @cindex standard dot notation, for Internet addresses
757 @cindex dot notation, for Internet addresses
758 There are four forms of the @dfn{standard numbers-and-dots notation}
759 for Internet addresses:
761 @table @code
762 @item @var{a}.@var{b}.@var{c}.@var{d}
763 This specifies all four bytes of the address individually.
765 @item @var{a}.@var{b}.@var{c}
766 The last part of the address, @var{c}, is interpreted as a 2-byte quantity.
767 This is useful for specifying host addresses in a Class B network with
768 network address number @code{@var{a}.@var{b}}.
770 @item @var{a}.@var{b}
771 The last part of the address, @var{c}, is interpreted as a 3-byte quantity.
772 This is useful for specifying host addresses in a Class A network with
773 network address number @var{a}.
775 @item @var{a}
776 If only one part is given, this corresponds directly to the host address
777 number.
778 @end table
780 Within each part of the address, the usual C conventions for specifying
781 the radix apply.  In other words, a leading @samp{0x} or @samp{0X} implies
782 hexadecimal radix; a leading @samp{0} implies octal; and otherwise decimal
783 radix is assumed.
785 @node Host Address Data Type
786 @subsubsection Host Address Data Type
788 Internet host addresses are represented in some contexts as integers
789 (type @code{unsigned long int}).  In other contexts, the integer is
790 packaged inside a structure of type @code{struct in_addr}.  It would
791 be better if the usage were made consistent, but it is not hard to extract
792 the integer from the structure or put the integer into a structure.
794 The following basic definitions for Internet addresses appear in the
795 header file @file{netinet/in.h}:
796 @pindex netinet/in.h
798 @comment netinet/in.h
799 @comment BSD
800 @deftp {Data Type} {struct in_addr}
801 This data type is used in certain contexts to contain an Internet host
802 address.  It has just one field, named @code{s_addr}, which records the
803 host address number as an @code{unsigned long int}.
804 @end deftp
806 @comment netinet/in.h
807 @comment BSD
808 @deftypevr Macro {unsigned int} INADDR_LOOPBACK
809 You can use this constant to stand for ``the address of this machine,''
810 instead of finding its actual address.  It is the Internet address
811 @samp{127.0.0.1}, which is usually called @samp{localhost}.  This
812 special constant saves you the trouble of looking up the address of your
813 own machine.  Also, the system usually implements @code{INADDR_LOOPBACK}
814 specially, avoiding any network traffic for the case of one machine
815 talking to itself.
816 @end deftypevr
818 @comment netinet/in.h
819 @comment BSD
820 @deftypevr Macro {unsigned int} INADDR_ANY
821 You can use this constant to stand for ``any incoming address,'' when
822 binding to an address.  @xref{Setting Address}.  This is the usual
823 address to give in the @code{sin_addr} member of @w{@code{struct
824 sockaddr_in}} when you want to accept Internet connections.
825 @end deftypevr
827 @comment netinet/in.h
828 @comment BSD
829 @deftypevr Macro {unsigned int} INADDR_BROADCAST
830 This constant is the address you use to send a broadcast message.
831 @c !!! broadcast needs further documented
832 @end deftypevr
834 @comment netinet/in.h
835 @comment BSD
836 @deftypevr Macro {unsigned int} INADDR_NONE
837 This constant is returned by some functions to indicate an error.
838 @end deftypevr
840 @comment netinet/in.h
841 @comment IPv6 basic API
842 @deftp {Data Type} {struct in6_addr}
843 This data type is used to store an IPv6 address.  It stores 128 bits of
844 data, which can be accessed (via a union) in a variety of ways.
845 @end deftp
847 @comment netinet/in.h
848 @comment IPv6 basic API
849 @deftypevr Constant {struct in6_addr} in6addr_loopback.
850 This constant is the IPv6 address @samp{::1}, the loopback address.  See
851 above for a description of what this means.  The macro
852 @code{IN6ADDR_LOOPBACK_INIT} is provided to allow you to initialise your
853 own variables to this value.
854 @end deftypevr
856 @comment netinet/in.h
857 @comment IPv6 basic API
858 @deftypevr Constant {struct in6_addr} in6addr_any
859 This constant is the IPv6 address @samp{::}, the unspecified address.  See
860 above for a description of what this means.  The macro
861 @code{IN6ADDR_ANY_INIT} is provided to allow you to initialise your
862 own variables to this value.
863 @end deftypevr
865 @node Host Address Functions
866 @subsubsection Host Address Functions
868 @pindex arpa/inet.h
869 These additional functions for manipulating Internet addresses are
870 declared in @file{arpa/inet.h}.  They represent Internet addresses in
871 network byte order; they represent network numbers and
872 local-address-within-network numbers in host byte order.
873 @xref{Byte Order}, for an explanation of network and host byte order.
875 @comment arpa/inet.h
876 @comment BSD
877 @deftypefun int inet_aton (const char *@var{name}, struct in_addr *@var{addr})
878 This function converts the Internet host address @var{name}
879 from the standard numbers-and-dots notation into binary data and stores
880 it in the @code{struct in_addr} that @var{addr} points to.
881 @code{inet_aton} returns nonzero if the address is valid, zero if not.
882 @end deftypefun
884 @comment arpa/inet.h
885 @comment BSD
886 @deftypefun {unsigned long int} inet_addr (const char *@var{name})
887 This function converts the Internet host address @var{name} from the
888 standard numbers-and-dots notation into binary data.  If the input is
889 not valid, @code{inet_addr} returns @code{INADDR_NONE}.  This is an
890 obsolete interface to @code{inet_aton}, described immediately above; it
891 is obsolete because @code{INADDR_NONE} is a valid address
892 (255.255.255.255), and @code{inet_aton} provides a cleaner way to
893 indicate error return.
894 @end deftypefun
896 @comment arpa/inet.h
897 @comment BSD
898 @deftypefun {unsigned long int} inet_network (const char *@var{name})
899 This function extracts the network number from the address @var{name},
900 given in the standard numbers-and-dots notation.
901 If the input is not valid, @code{inet_network} returns @code{-1}.
902 @end deftypefun
904 @comment arpa/inet.h
905 @comment BSD
906 @deftypefun {char *} inet_ntoa (struct in_addr @var{addr})
907 This function converts the Internet host address @var{addr} to a
908 string in the standard numbers-and-dots notation.  The return value is
909 a pointer into a statically-allocated buffer.  Subsequent calls will
910 overwrite the same buffer, so you should copy the string if you need
911 to save it.
913 In multi-threaded programs each thread has an own statically-allocated
914 buffer.  But still subsequent calls of @code{inet_ntoa} in the same
915 thread will overwrite the result of the last call.
916 @end deftypefun
918 @comment arpa/inet.h
919 @comment BSD
920 @deftypefun {struct in_addr} inet_makeaddr (int @var{net}, int @var{local})
921 This function makes an Internet host address by combining the network
922 number @var{net} with the local-address-within-network number
923 @var{local}.
924 @end deftypefun
926 @comment arpa/inet.h
927 @comment BSD
928 @deftypefun int inet_lnaof (struct in_addr @var{addr})
929 This function returns the local-address-within-network part of the
930 Internet host address @var{addr}.
931 @end deftypefun
933 @comment arpa/inet.h
934 @comment BSD
935 @deftypefun int inet_netof (struct in_addr @var{addr})
936 This function returns the network number part of the Internet host
937 address @var{addr}.
938 @end deftypefun
940 @comment arpa/inet.h
941 @comment IPv6 basic API
942 @deftypefun int inet_pton (int @var{af}, const char *@var{cp}, void *@var{buf})
943 This function converts an Internet address (either IPv4 or IPv6) from
944 presentation (textual) to network (binary) format.  @var{af} should be
945 either @code{AF_INET} or @code{AF_INET6}, as appropriate for the type of
946 address being converted.  @var{cp} is a pointer to the input string, and
947 @var{buf} is a pointer to a buffer for the result.  It is the caller's
948 responsibility to make sure the buffer is large enough.
949 @end deftypefun
951 @comment arpa/inet.h
952 @comment IPv6 basic API
953 @deftypefun {char *} inet_ntop (int @var{af}, const void *@var{cp}, char *@var{buf}, size_t @var{len})
954 This function converts an Internet address (either IPv4 or IPv6) from
955 network (binary) to presentation (textual) form.  @var{af} should be
956 either @code{AF_INET} or @code{AF_INET6}, as appropriate.  @var{cp} is a
957 pointer to the address to be converted.  @var{buf} should be a pointer
958 to a buffer to hold the result, and @var{len} is the length of this
959 buffer.  The return value from the function will be this buffer address.
960 @end deftypefun
962 @node Host Names
963 @subsubsection Host Names
964 @cindex hosts database
965 @cindex converting host name to address
966 @cindex converting host address to name
968 Besides the standard numbers-and-dots notation for Internet addresses,
969 you can also refer to a host by a symbolic name.  The advantage of a
970 symbolic name is that it is usually easier to remember.  For example,
971 the machine with Internet address @samp{128.52.46.32} is also known as
972 @samp{churchy.gnu.ai.mit.edu}; and other machines in the @samp{gnu.ai.mit.edu}
973 domain can refer to it simply as @samp{churchy}.
975 @pindex /etc/hosts
976 @pindex netdb.h
977 Internally, the system uses a database to keep track of the mapping
978 between host names and host numbers.  This database is usually either
979 the file @file{/etc/hosts} or an equivalent provided by a name server.
980 The functions and other symbols for accessing this database are declared
981 in @file{netdb.h}.  They are BSD features, defined unconditionally if
982 you include @file{netdb.h}.
984 @comment netdb.h
985 @comment BSD
986 @deftp {Data Type} {struct hostent}
987 This data type is used to represent an entry in the hosts database.  It
988 has the following members:
990 @table @code
991 @item char *h_name
992 This is the ``official'' name of the host.
994 @item char **h_aliases
995 These are alternative names for the host, represented as a null-terminated
996 vector of strings.
998 @item int h_addrtype
999 This is the host address type; in practice, its value is always either
1000 @code{AF_INET} or @code{AF_INET6}, with the latter being used for IPv6
1001 hosts.  In principle other kinds of addresses could be represented in
1002 the data base as well as Internet addresses; if this were done, you
1003 might find a value in this field other than @code{AF_INET} or
1004 @code{AF_INET6}.  @xref{Socket Addresses}.
1006 @item int h_length
1007 This is the length, in bytes, of each address.
1009 @item char **h_addr_list
1010 This is the vector of addresses for the host.  (Recall that the host
1011 might be connected to multiple networks and have different addresses on
1012 each one.)  The vector is terminated by a null pointer.
1014 @item char *h_addr
1015 This is a synonym for @code{h_addr_list[0]}; in other words, it is the
1016 first host address.
1017 @end table
1018 @end deftp
1020 As far as the host database is concerned, each address is just a block
1021 of memory @code{h_length} bytes long.  But in other contexts there is an
1022 implicit assumption that you can convert this to a @code{struct in_addr} or
1023 an @code{unsigned long int}.  Host addresses in a @code{struct hostent}
1024 structure are always given in network byte order; see @ref{Byte Order}.
1026 You can use @code{gethostbyname}, @code{gethostbyname2} or
1027 @code{gethostbyaddr} to search the hosts database for information about
1028 a particular host.  The information is returned in a
1029 statically-allocated structure; you must copy the information if you
1030 need to save it across calls.  You can also use @code{getaddrinfo} and
1031 @code{getnameinfo} to obtain this information.
1033 @comment netdb.h
1034 @comment BSD
1035 @deftypefun {struct hostent *} gethostbyname (const char *@var{name})
1036 The @code{gethostbyname} function returns information about the host
1037 named @var{name}.  If the lookup fails, it returns a null pointer.
1038 @end deftypefun
1040 @comment netdb.h
1041 @comment IPv6 Basic API
1042 @deftypefun {struct hostent *} gethostbyname2 (const char *@var{name}, int @var{af})
1043 The @code{gethostbyname2} function is like @code{gethostbyname}, but
1044 allows the caller to specify the desired address family (e.g.@:
1045 @code{AF_INET} or @code{AF_INET6}) for the result.
1046 @end deftypefun
1048 @comment netdb.h
1049 @comment BSD
1050 @deftypefun {struct hostent *} gethostbyaddr (const char *@var{addr}, int @var{length}, int @var{format})
1051 The @code{gethostbyaddr} function returns information about the host
1052 with Internet address @var{addr}.  The @var{length} argument is the
1053 size (in bytes) of the address at @var{addr}.  @var{format} specifies
1054 the address format; for an Internet address, specify a value of
1055 @code{AF_INET}.
1057 If the lookup fails, @code{gethostbyaddr} returns a null pointer.
1058 @end deftypefun
1060 @vindex h_errno
1061 If the name lookup by @code{gethostbyname} or @code{gethostbyaddr}
1062 fails, you can find out the reason by looking at the value of the
1063 variable @code{h_errno}.  (It would be cleaner design for these
1064 functions to set @code{errno}, but use of @code{h_errno} is compatible
1065 with other systems.)  Before using @code{h_errno}, you must declare it
1066 like this:
1068 @smallexample
1069 extern int h_errno;
1070 @end smallexample
1072 Here are the error codes that you may find in @code{h_errno}:
1074 @table @code
1075 @comment netdb.h
1076 @comment BSD
1077 @item HOST_NOT_FOUND
1078 @vindex HOST_NOT_FOUND
1079 No such host is known in the data base.
1081 @comment netdb.h
1082 @comment BSD
1083 @item TRY_AGAIN
1084 @vindex TRY_AGAIN
1085 This condition happens when the name server could not be contacted.  If
1086 you try again later, you may succeed then.
1088 @comment netdb.h
1089 @comment BSD
1090 @item NO_RECOVERY
1091 @vindex NO_RECOVERY
1092 A non-recoverable error occurred.
1094 @comment netdb.h
1095 @comment BSD
1096 @item NO_ADDRESS
1097 @vindex NO_ADDRESS
1098 The host database contains an entry for the name, but it doesn't have an
1099 associated Internet address.
1100 @end table
1102 You can also scan the entire hosts database one entry at a time using
1103 @code{sethostent}, @code{gethostent}, and @code{endhostent}.  Be careful
1104 in using these functions, because they are not reentrant.
1106 @comment netdb.h
1107 @comment BSD
1108 @deftypefun void sethostent (int @var{stayopen})
1109 This function opens the hosts database to begin scanning it.  You can
1110 then call @code{gethostent} to read the entries.
1112 @c There was a rumor that this flag has different meaning if using the DNS,
1113 @c but it appears this description is accurate in that case also.
1114 If the @var{stayopen} argument is nonzero, this sets a flag so that
1115 subsequent calls to @code{gethostbyname} or @code{gethostbyaddr} will
1116 not close the database (as they usually would).  This makes for more
1117 efficiency if you call those functions several times, by avoiding
1118 reopening the database for each call.
1119 @end deftypefun
1121 @comment netdb.h
1122 @comment BSD
1123 @deftypefun {struct hostent *} gethostent ()
1124 This function returns the next entry in the hosts database.  It
1125 returns a null pointer if there are no more entries.
1126 @end deftypefun
1128 @comment netdb.h
1129 @comment BSD
1130 @deftypefun void endhostent ()
1131 This function closes the hosts database.
1132 @end deftypefun
1134 @node Ports
1135 @subsection Internet Ports
1136 @cindex port number
1138 A socket address in the Internet namespace consists of a machine's
1139 Internet address plus a @dfn{port number} which distinguishes the
1140 sockets on a given machine (for a given protocol).  Port numbers range
1141 from 0 to 65,535.
1143 Port numbers less than @code{IPPORT_RESERVED} are reserved for standard
1144 servers, such as @code{finger} and @code{telnet}.  There is a database
1145 that keeps track of these, and you can use the @code{getservbyname}
1146 function to map a service name onto a port number; see @ref{Services
1147 Database}.
1149 If you write a server that is not one of the standard ones defined in
1150 the database, you must choose a port number for it.  Use a number
1151 greater than @code{IPPORT_USERRESERVED}; such numbers are reserved for
1152 servers and won't ever be generated automatically by the system.
1153 Avoiding conflicts with servers being run by other users is up to you.
1155 When you use a socket without specifying its address, the system
1156 generates a port number for it.  This number is between
1157 @code{IPPORT_RESERVED} and @code{IPPORT_USERRESERVED}.
1159 On the Internet, it is actually legitimate to have two different
1160 sockets with the same port number, as long as they never both try to
1161 communicate with the same socket address (host address plus port
1162 number).  You shouldn't duplicate a port number except in special
1163 circumstances where a higher-level protocol requires it.  Normally,
1164 the system won't let you do it; @code{bind} normally insists on
1165 distinct port numbers.  To reuse a port number, you must set the
1166 socket option @code{SO_REUSEADDR}.  @xref{Socket-Level Options}.
1168 @pindex netinet/in.h
1169 These macros are defined in the header file @file{netinet/in.h}.
1171 @comment netinet/in.h
1172 @comment BSD
1173 @deftypevr Macro int IPPORT_RESERVED
1174 Port numbers less than @code{IPPORT_RESERVED} are reserved for
1175 superuser use.
1176 @end deftypevr
1178 @comment netinet/in.h
1179 @comment BSD
1180 @deftypevr Macro int IPPORT_USERRESERVED
1181 Port numbers greater than or equal to @code{IPPORT_USERRESERVED} are
1182 reserved for explicit use; they will never be allocated automatically.
1183 @end deftypevr
1185 @node Services Database
1186 @subsection The Services Database
1187 @cindex services database
1188 @cindex converting service name to port number
1189 @cindex converting port number to service name
1191 @pindex /etc/services
1192 The database that keeps track of ``well-known'' services is usually
1193 either the file @file{/etc/services} or an equivalent from a name server.
1194 You can use these utilities, declared in @file{netdb.h}, to access
1195 the services database.
1196 @pindex netdb.h
1198 @comment netdb.h
1199 @comment BSD
1200 @deftp {Data Type} {struct servent}
1201 This data type holds information about entries from the services database.
1202 It has the following members:
1204 @table @code
1205 @item char *s_name
1206 This is the ``official'' name of the service.
1208 @item char **s_aliases
1209 These are alternate names for the service, represented as an array of
1210 strings.  A null pointer terminates the array.
1212 @item int s_port
1213 This is the port number for the service.  Port numbers are given in
1214 network byte order; see @ref{Byte Order}.
1216 @item char *s_proto
1217 This is the name of the protocol to use with this service.
1218 @xref{Protocols Database}.
1219 @end table
1220 @end deftp
1222 To get information about a particular service, use the
1223 @code{getservbyname} or @code{getservbyport} functions.  The information
1224 is returned in a statically-allocated structure; you must copy the
1225 information if you need to save it across calls.
1227 @comment netdb.h
1228 @comment BSD
1229 @deftypefun {struct servent *} getservbyname (const char *@var{name}, const char *@var{proto})
1230 The @code{getservbyname} function returns information about the
1231 service named @var{name} using protocol @var{proto}.  If it can't find
1232 such a service, it returns a null pointer.
1234 This function is useful for servers as well as for clients; servers
1235 use it to determine which port they should listen on (@pxref{Listening}).
1236 @end deftypefun
1238 @comment netdb.h
1239 @comment BSD
1240 @deftypefun {struct servent *} getservbyport (int @var{port}, const char *@var{proto})
1241 The @code{getservbyport} function returns information about the
1242 service at port @var{port} using protocol @var{proto}.  If it can't
1243 find such a service, it returns a null pointer.
1244 @end deftypefun
1246 You can also scan the services database using @code{setservent},
1247 @code{getservent}, and @code{endservent}.  Be careful in using these
1248 functions, because they are not reentrant.
1250 @comment netdb.h
1251 @comment BSD
1252 @deftypefun void setservent (int @var{stayopen})
1253 This function opens the services database to begin scanning it.
1255 If the @var{stayopen} argument is nonzero, this sets a flag so that
1256 subsequent calls to @code{getservbyname} or @code{getservbyport} will
1257 not close the database (as they usually would).  This makes for more
1258 efficiency if you call those functions several times, by avoiding
1259 reopening the database for each call.
1260 @end deftypefun
1262 @comment netdb.h
1263 @comment BSD
1264 @deftypefun {struct servent *} getservent (void)
1265 This function returns the next entry in the services database.  If
1266 there are no more entries, it returns a null pointer.
1267 @end deftypefun
1269 @comment netdb.h
1270 @comment BSD
1271 @deftypefun void endservent (void)
1272 This function closes the services database.
1273 @end deftypefun
1275 @node Byte Order
1276 @subsection Byte Order Conversion
1277 @cindex byte order conversion, for socket
1278 @cindex converting byte order
1280 @cindex big-endian
1281 @cindex little-endian
1282 Different kinds of computers use different conventions for the
1283 ordering of bytes within a word.  Some computers put the most
1284 significant byte within a word first (this is called ``big-endian''
1285 order), and others put it last (``little-endian'' order).
1287 @cindex network byte order
1288 So that machines with different byte order conventions can
1289 communicate, the Internet protocols specify a canonical byte order
1290 convention for data transmitted over the network.  This is known
1291 as the @dfn{network byte order}.
1293 When establishing an Internet socket connection, you must make sure that
1294 the data in the @code{sin_port} and @code{sin_addr} members of the
1295 @code{sockaddr_in} structure are represented in the network byte order.
1296 If you are encoding integer data in the messages sent through the
1297 socket, you should convert this to network byte order too.  If you don't
1298 do this, your program may fail when running on or talking to other kinds
1299 of machines.
1301 If you use @code{getservbyname} and @code{gethostbyname} or
1302 @code{inet_addr} to get the port number and host address, the values are
1303 already in the network byte order, and you can copy them directly into
1304 the @code{sockaddr_in} structure.
1306 Otherwise, you have to convert the values explicitly.  Use
1307 @code{htons} and @code{ntohs} to convert values for the @code{sin_port}
1308 member.  Use @code{htonl} and @code{ntohl} to convert values for the
1309 @code{sin_addr} member.  (Remember, @code{struct in_addr} is equivalent
1310 to @code{unsigned long int}.)  These functions are declared in
1311 @file{netinet/in.h}.
1312 @pindex netinet/in.h
1314 @comment netinet/in.h
1315 @comment BSD
1316 @deftypefun {unsigned short int} htons (unsigned short int @var{hostshort})
1317 This function converts the @code{short} integer @var{hostshort} from
1318 host byte order to network byte order.
1319 @end deftypefun
1321 @comment netinet/in.h
1322 @comment BSD
1323 @deftypefun {unsigned short int} ntohs (unsigned short int @var{netshort})
1324 This function converts the @code{short} integer @var{netshort} from
1325 network byte order to host byte order.
1326 @end deftypefun
1328 @comment netinet/in.h
1329 @comment BSD
1330 @deftypefun {unsigned long int} htonl (unsigned long int @var{hostlong})
1331 This function converts the @code{long} integer @var{hostlong} from
1332 host byte order to network byte order.
1333 @end deftypefun
1335 @comment netinet/in.h
1336 @comment BSD
1337 @deftypefun {unsigned long int} ntohl (unsigned long int @var{netlong})
1338 This function converts the @code{long} integer @var{netlong} from
1339 network byte order to host byte order.
1340 @end deftypefun
1342 @node Protocols Database
1343 @subsection Protocols Database
1344 @cindex protocols database
1346 The communications protocol used with a socket controls low-level
1347 details of how data is exchanged.  For example, the protocol implements
1348 things like checksums to detect errors in transmissions, and routing
1349 instructions for messages.  Normal user programs have little reason to
1350 mess with these details directly.
1352 @cindex TCP (Internet protocol)
1353 The default communications protocol for the Internet namespace depends on
1354 the communication style.  For stream communication, the default is TCP
1355 (``transmission control protocol'').  For datagram communication, the
1356 default is UDP (``user datagram protocol'').  For reliable datagram
1357 communication, the default is RDP (``reliable datagram protocol'').
1358 You should nearly always use the default.
1360 @pindex /etc/protocols
1361 Internet protocols are generally specified by a name instead of a
1362 number.  The network protocols that a host knows about are stored in a
1363 database.  This is usually either derived from the file
1364 @file{/etc/protocols}, or it may be an equivalent provided by a name
1365 server.  You look up the protocol number associated with a named
1366 protocol in the database using the @code{getprotobyname} function.
1368 Here are detailed descriptions of the utilities for accessing the
1369 protocols database.  These are declared in @file{netdb.h}.
1370 @pindex netdb.h
1372 @comment netdb.h
1373 @comment BSD
1374 @deftp {Data Type} {struct protoent}
1375 This data type is used to represent entries in the network protocols
1376 database.  It has the following members:
1378 @table @code
1379 @item char *p_name
1380 This is the official name of the protocol.
1382 @item char **p_aliases
1383 These are alternate names for the protocol, specified as an array of
1384 strings.  The last element of the array is a null pointer.
1386 @item int p_proto
1387 This is the protocol number (in host byte order); use this member as the
1388 @var{protocol} argument to @code{socket}.
1389 @end table
1390 @end deftp
1392 You can use @code{getprotobyname} and @code{getprotobynumber} to search
1393 the protocols database for a specific protocol.  The information is
1394 returned in a statically-allocated structure; you must copy the
1395 information if you need to save it across calls.
1397 @comment netdb.h
1398 @comment BSD
1399 @deftypefun {struct protoent *} getprotobyname (const char *@var{name})
1400 The @code{getprotobyname} function returns information about the
1401 network protocol named @var{name}.  If there is no such protocol, it
1402 returns a null pointer.
1403 @end deftypefun
1405 @comment netdb.h
1406 @comment BSD
1407 @deftypefun {struct protoent *} getprotobynumber (int @var{protocol})
1408 The @code{getprotobynumber} function returns information about the
1409 network protocol with number @var{protocol}.  If there is no such
1410 protocol, it returns a null pointer.
1411 @end deftypefun
1413 You can also scan the whole protocols database one protocol at a time by
1414 using @code{setprotoent}, @code{getprotoent}, and @code{endprotoent}.
1415 Be careful in using these functions, because they are not reentrant.
1417 @comment netdb.h
1418 @comment BSD
1419 @deftypefun void setprotoent (int @var{stayopen})
1420 This function opens the protocols database to begin scanning it.
1422 If the @var{stayopen} argument is nonzero, this sets a flag so that
1423 subsequent calls to @code{getprotobyname} or @code{getprotobynumber} will
1424 not close the database (as they usually would).  This makes for more
1425 efficiency if you call those functions several times, by avoiding
1426 reopening the database for each call.
1427 @end deftypefun
1429 @comment netdb.h
1430 @comment BSD
1431 @deftypefun {struct protoent *} getprotoent (void)
1432 This function returns the next entry in the protocols database.  It
1433 returns a null pointer if there are no more entries.
1434 @end deftypefun
1436 @comment netdb.h
1437 @comment BSD
1438 @deftypefun void endprotoent (void)
1439 This function closes the protocols database.
1440 @end deftypefun
1442 @node Inet Example
1443 @subsection Internet Socket Example
1445 Here is an example showing how to create and name a socket in the
1446 Internet namespace.  The newly created socket exists on the machine that
1447 the program is running on.  Rather than finding and using the machine's
1448 Internet address, this example specifies @code{INADDR_ANY} as the host
1449 address; the system replaces that with the machine's actual address.
1451 @smallexample
1452 @include mkisock.c.texi
1453 @end smallexample
1455 Here is another example, showing how you can fill in a @code{sockaddr_in}
1456 structure, given a host name string and a port number:
1458 @smallexample
1459 @include isockad.c.texi
1460 @end smallexample
1462 @node Misc Namespaces
1463 @section Other Namespaces
1465 @vindex PF_NS
1466 @vindex PF_ISO
1467 @vindex PF_CCITT
1468 @vindex PF_IMPLINK
1469 @vindex PF_ROUTE
1470 Certain other namespaces and associated protocol families are supported
1471 but not documented yet because they are not often used.  @code{PF_NS}
1472 refers to the Xerox Network Software protocols.  @code{PF_ISO} stands
1473 for Open Systems Interconnect.  @code{PF_CCITT} refers to protocols from
1474 CCITT.  @file{socket.h} defines these symbols and others naming protocols
1475 not actually implemented.
1477 @code{PF_IMPLINK} is used for communicating between hosts and Internet
1478 Message Processors.  For information on this, and on @code{PF_ROUTE}, an
1479 occasionally-used local area routing protocol, see the GNU Hurd Manual
1480 (to appear in the future).
1482 @node Open/Close Sockets
1483 @section Opening and Closing Sockets
1485 This section describes the actual library functions for opening and
1486 closing sockets.  The same functions work for all namespaces and
1487 connection styles.
1489 @menu
1490 * Creating a Socket::           How to open a socket.
1491 * Closing a Socket::            How to close a socket.
1492 * Socket Pairs::                These are created like pipes.
1493 @end menu
1495 @node Creating a Socket
1496 @subsection Creating a Socket
1497 @cindex creating a socket
1498 @cindex socket, creating
1499 @cindex opening a socket
1501 The primitive for creating a socket is the @code{socket} function,
1502 declared in @file{sys/socket.h}.
1503 @pindex sys/socket.h
1505 @comment sys/socket.h
1506 @comment BSD
1507 @deftypefun int socket (int @var{namespace}, int @var{style}, int @var{protocol})
1508 This function creates a socket and specifies communication style
1509 @var{style}, which should be one of the socket styles listed in
1510 @ref{Communication Styles}.  The @var{namespace} argument specifies
1511 the namespace; it must be @code{PF_FILE} (@pxref{File Namespace}) or
1512 @code{PF_INET} (@pxref{Internet Namespace}).  @var{protocol}
1513 designates the specific protocol (@pxref{Socket Concepts}); zero is
1514 usually right for @var{protocol}.
1516 The return value from @code{socket} is the file descriptor for the new
1517 socket, or @code{-1} in case of error.  The following @code{errno} error
1518 conditions are defined for this function:
1520 @table @code
1521 @item EPROTONOSUPPORT
1522 The @var{protocol} or @var{style} is not supported by the
1523 @var{namespace} specified.
1525 @item EMFILE
1526 The process already has too many file descriptors open.
1528 @item ENFILE
1529 The system already has too many file descriptors open.
1531 @item EACCESS
1532 The process does not have privilege to create a socket of the specified
1533 @var{style} or @var{protocol}.
1535 @item ENOBUFS
1536 The system ran out of internal buffer space.
1537 @end table
1539 The file descriptor returned by the @code{socket} function supports both
1540 read and write operations.  But, like pipes, sockets do not support file
1541 positioning operations.
1542 @end deftypefun
1544 For examples of how to call the @code{socket} function,
1545 see @ref{File Namespace}, or @ref{Inet Example}.
1548 @node Closing a Socket
1549 @subsection Closing a Socket
1550 @cindex socket, closing
1551 @cindex closing a socket
1552 @cindex shutting down a socket
1553 @cindex socket shutdown
1555 When you are finished using a socket, you can simply close its
1556 file descriptor with @code{close}; see @ref{Opening and Closing Files}.
1557 If there is still data waiting to be transmitted over the connection,
1558 normally @code{close} tries to complete this transmission.  You
1559 can control this behavior using the @code{SO_LINGER} socket option to
1560 specify a timeout period; see @ref{Socket Options}.
1562 @pindex sys/socket.h
1563 You can also shut down only reception or only transmission on a
1564 connection by calling @code{shutdown}, which is declared in
1565 @file{sys/socket.h}.
1567 @comment sys/socket.h
1568 @comment BSD
1569 @deftypefun int shutdown (int @var{socket}, int @var{how})
1570 The @code{shutdown} function shuts down the connection of socket
1571 @var{socket}.  The argument @var{how} specifies what action to
1572 perform:
1574 @table @code
1575 @item 0
1576 Stop receiving data for this socket.  If further data arrives,
1577 reject it.
1579 @item 1
1580 Stop trying to transmit data from this socket.  Discard any data
1581 waiting to be sent.  Stop looking for acknowledgement of data already
1582 sent; don't retransmit it if it is lost.
1584 @item 2
1585 Stop both reception and transmission.
1586 @end table
1588 The return value is @code{0} on success and @code{-1} on failure.  The
1589 following @code{errno} error conditions are defined for this function:
1591 @table @code
1592 @item EBADF
1593 @var{socket} is not a valid file descriptor.
1595 @item ENOTSOCK
1596 @var{socket} is not a socket.
1598 @item ENOTCONN
1599 @var{socket} is not connected.
1600 @end table
1601 @end deftypefun
1603 @node Socket Pairs
1604 @subsection Socket Pairs
1605 @cindex creating a socket pair
1606 @cindex socket pair
1607 @cindex opening a socket pair
1609 @pindex sys/socket.h
1610 A @dfn{socket pair} consists of a pair of connected (but unnamed)
1611 sockets.  It is very similar to a pipe and is used in much the same
1612 way.  Socket pairs are created with the @code{socketpair} function,
1613 declared in @file{sys/socket.h}.  A socket pair is much like a pipe; the
1614 main difference is that the socket pair is bidirectional, whereas the
1615 pipe has one input-only end and one output-only end (@pxref{Pipes and
1616 FIFOs}).
1618 @comment sys/socket.h
1619 @comment BSD
1620 @deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})
1621 This function creates a socket pair, returning the file descriptors in
1622 @code{@var{filedes}[0]} and @code{@var{filedes}[1]}.  The socket pair
1623 is a full-duplex communications channel, so that both reading and writing
1624 may be performed at either end.
1626 The @var{namespace}, @var{style}, and @var{protocol} arguments are
1627 interpreted as for the @code{socket} function.  @var{style} should be
1628 one of the communication styles listed in @ref{Communication Styles}.
1629 The @var{namespace} argument specifies the namespace, which must be
1630 @code{AF_FILE} (@pxref{File Namespace}); @var{protocol} specifies the
1631 communications protocol, but zero is the only meaningful value.
1633 If @var{style} specifies a connectionless communication style, then
1634 the two sockets you get are not @emph{connected}, strictly speaking,
1635 but each of them knows the other as the default destination address,
1636 so they can send packets to each other.
1638 The @code{socketpair} function returns @code{0} on success and @code{-1}
1639 on failure.  The following @code{errno} error conditions are defined
1640 for this function:
1642 @table @code
1643 @item EMFILE
1644 The process has too many file descriptors open.
1646 @item EAFNOSUPPORT
1647 The specified namespace is not supported.
1649 @item EPROTONOSUPPORT
1650 The specified protocol is not supported.
1652 @item EOPNOTSUPP
1653 The specified protocol does not support the creation of socket pairs.
1654 @end table
1655 @end deftypefun
1657 @node Connections
1658 @section Using Sockets with Connections
1660 @cindex connection
1661 @cindex client
1662 @cindex server
1663 The most common communication styles involve making a connection to a
1664 particular other socket, and then exchanging data with that socket
1665 over and over.  Making a connection is asymmetric; one side (the
1666 @dfn{client}) acts to request a connection, while the other side (the
1667 @dfn{server}) makes a socket and waits for the connection request.
1669 @iftex
1670 @itemize @bullet
1671 @item
1672 @ref{Connecting}, describes what the client program must do to
1673 initiate a connection with a server.
1675 @item
1676 @ref{Listening}, and @ref{Accepting Connections}, describe what the
1677 server program must do to wait for and act upon connection requests
1678 from clients.
1680 @item
1681 @ref{Transferring Data}, describes how data is transferred through the
1682 connected socket.
1683 @end itemize
1684 @end iftex
1686 @menu
1687 * Connecting::               What the client program must do.
1688 * Listening::                How a server program waits for requests.
1689 * Accepting Connections::    What the server does when it gets a request.
1690 * Who is Connected::         Getting the address of the
1691                                 other side of a connection.
1692 * Transferring Data::        How to send and receive data.
1693 * Byte Stream Example::      An example program: a client for communicating
1694                               over a byte stream socket in the Internet namespace.
1695 * Server Example::           A corresponding server program.
1696 * Out-of-Band Data::         This is an advanced feature.
1697 @end menu
1699 @node Connecting
1700 @subsection Making a Connection
1701 @cindex connecting a socket
1702 @cindex socket, connecting
1703 @cindex socket, initiating a connection
1704 @cindex socket, client actions
1706 In making a connection, the client makes a connection while the server
1707 waits for and accepts the connection.  Here we discuss what the client
1708 program must do, using the @code{connect} function, which is declared in
1709 @file{sys/socket.h}.
1711 @comment sys/socket.h
1712 @comment BSD
1713 @deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, socklen_t @var{length})
1714 The @code{connect} function initiates a connection from the socket
1715 with file descriptor @var{socket} to the socket whose address is
1716 specified by the @var{addr} and @var{length} arguments.  (This socket
1717 is typically on another machine, and it must be already set up as a
1718 server.)  @xref{Socket Addresses}, for information about how these
1719 arguments are interpreted.
1721 Normally, @code{connect} waits until the server responds to the request
1722 before it returns.  You can set nonblocking mode on the socket
1723 @var{socket} to make @code{connect} return immediately without waiting
1724 for the response.  @xref{File Status Flags}, for information about
1725 nonblocking mode.
1726 @c !!! how do you tell when it has finished connecting?  I suspect the
1727 @c way you do it is select for writing.
1729 The normal return value from @code{connect} is @code{0}.  If an error
1730 occurs, @code{connect} returns @code{-1}.  The following @code{errno}
1731 error conditions are defined for this function:
1733 @table @code
1734 @item EBADF
1735 The socket @var{socket} is not a valid file descriptor.
1737 @item ENOTSOCK
1738 File descriptor @var{socket} is not a socket.
1740 @item EADDRNOTAVAIL
1741 The specified address is not available on the remote machine.
1743 @item EAFNOSUPPORT
1744 The namespace of the @var{addr} is not supported by this socket.
1746 @item EISCONN
1747 The socket @var{socket} is already connected.
1749 @item ETIMEDOUT
1750 The attempt to establish the connection timed out.
1752 @item ECONNREFUSED
1753 The server has actively refused to establish the connection.
1755 @item ENETUNREACH
1756 The network of the given @var{addr} isn't reachable from this host.
1758 @item EADDRINUSE
1759 The socket address of the given @var{addr} is already in use.
1761 @item EINPROGRESS
1762 The socket @var{socket} is non-blocking and the connection could not be
1763 established immediately.  You can determine when the connection is
1764 completely established with @code{select}; @pxref{Waiting for I/O}.
1765 Another @code{connect} call on the same socket, before the connection is
1766 completely established, will fail with @code{EALREADY}.
1768 @item EALREADY
1769 The socket @var{socket} is non-blocking and already has a pending
1770 connection in progress (see @code{EINPROGRESS} above).
1771 @end table
1772 @end deftypefun
1774 @node Listening
1775 @subsection Listening for Connections
1776 @cindex listening (sockets)
1777 @cindex sockets, server actions
1778 @cindex sockets, listening
1780 Now let us consider what the server process must do to accept
1781 connections on a socket.  First it must use the @code{listen} function
1782 to enable connection requests on the socket, and then accept each
1783 incoming connection with a call to @code{accept} (@pxref{Accepting
1784 Connections}).  Once connection requests are enabled on a server socket,
1785 the @code{select} function reports when the socket has a connection
1786 ready to be accepted (@pxref{Waiting for I/O}).
1788 The @code{listen} function is not allowed for sockets using
1789 connectionless communication styles.
1791 You can write a network server that does not even start running until a
1792 connection to it is requested.  @xref{Inetd Servers}.
1794 In the Internet namespace, there are no special protection mechanisms
1795 for controlling access to connect to a port; any process on any machine
1796 can make a connection to your server.  If you want to restrict access to
1797 your server, make it examine the addresses associated with connection
1798 requests or implement some other handshaking or identification
1799 protocol.
1801 In the File namespace, the ordinary file protection bits control who has
1802 access to connect to the socket.
1804 @comment sys/socket.h
1805 @comment BSD
1806 @deftypefun int listen (int @var{socket}, unsigned int @var{n})
1807 The @code{listen} function enables the socket @var{socket} to accept
1808 connections, thus making it a server socket.
1810 The argument @var{n} specifies the length of the queue for pending
1811 connections.  When the queue fills, new clients attempting to connect
1812 fail with @code{ECONNREFUSED} until the server calls @code{accept} to
1813 accept a connection from the queue.
1815 The @code{listen} function returns @code{0} on success and @code{-1}
1816 on failure.  The following @code{errno} error conditions are defined
1817 for this function:
1819 @table @code
1820 @item EBADF
1821 The argument @var{socket} is not a valid file descriptor.
1823 @item ENOTSOCK
1824 The argument @var{socket} is not a socket.
1826 @item EOPNOTSUPP
1827 The socket @var{socket} does not support this operation.
1828 @end table
1829 @end deftypefun
1831 @node Accepting Connections
1832 @subsection Accepting Connections
1833 @cindex sockets, accepting connections
1834 @cindex accepting connections
1836 When a server receives a connection request, it can complete the
1837 connection by accepting the request.  Use the function @code{accept}
1838 to do this.
1840 A socket that has been established as a server can accept connection
1841 requests from multiple clients.  The server's original socket
1842 @emph{does not become part} of the connection; instead, @code{accept}
1843 makes a new socket which participates in the connection.
1844 @code{accept} returns the descriptor for this socket.  The server's
1845 original socket remains available for listening for further connection
1846 requests.
1848 The number of pending connection requests on a server socket is finite.
1849 If connection requests arrive from clients faster than the server can
1850 act upon them, the queue can fill up and additional requests are refused
1851 with a @code{ECONNREFUSED} error.  You can specify the maximum length of
1852 this queue as an argument to the @code{listen} function, although the
1853 system may also impose its own internal limit on the length of this
1854 queue.
1856 @comment sys/socket.h
1857 @comment BSD
1858 @deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, socklen_t *@var{length-ptr})
1859 This function is used to accept a connection request on the server
1860 socket @var{socket}.
1862 The @code{accept} function waits if there are no connections pending,
1863 unless the socket @var{socket} has nonblocking mode set.  (You can use
1864 @code{select} to wait for a pending connection, with a nonblocking
1865 socket.)  @xref{File Status Flags}, for information about nonblocking
1866 mode.
1868 The @var{addr} and @var{length-ptr} arguments are used to return
1869 information about the name of the client socket that initiated the
1870 connection.  @xref{Socket Addresses}, for information about the format
1871 of the information.
1873 Accepting a connection does not make @var{socket} part of the
1874 connection.  Instead, it creates a new socket which becomes
1875 connected.  The normal return value of @code{accept} is the file
1876 descriptor for the new socket.
1878 After @code{accept}, the original socket @var{socket} remains open and
1879 unconnected, and continues listening until you close it.  You can
1880 accept further connections with @var{socket} by calling @code{accept}
1881 again.
1883 If an error occurs, @code{accept} returns @code{-1}.  The following
1884 @code{errno} error conditions are defined for this function:
1886 @table @code
1887 @item EBADF
1888 The @var{socket} argument is not a valid file descriptor.
1890 @item ENOTSOCK
1891 The descriptor @var{socket} argument is not a socket.
1893 @item EOPNOTSUPP
1894 The descriptor @var{socket} does not support this operation.
1896 @item EWOULDBLOCK
1897 @var{socket} has nonblocking mode set, and there are no pending
1898 connections immediately available.
1899 @end table
1900 @end deftypefun
1902 The @code{accept} function is not allowed for sockets using
1903 connectionless communication styles.
1905 @node Who is Connected
1906 @subsection Who is Connected to Me?
1908 @comment sys/socket.h
1909 @comment BSD
1910 @deftypefun int getpeername (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
1911 The @code{getpeername} function returns the address of the socket that
1912 @var{socket} is connected to; it stores the address in the memory space
1913 specified by @var{addr} and @var{length-ptr}.  It stores the length of
1914 the address in @code{*@var{length-ptr}}.
1916 @xref{Socket Addresses}, for information about the format of the
1917 address.  In some operating systems, @code{getpeername} works only for
1918 sockets in the Internet domain.
1920 The return value is @code{0} on success and @code{-1} on error.  The
1921 following @code{errno} error conditions are defined for this function:
1923 @table @code
1924 @item EBADF
1925 The argument @var{socket} is not a valid file descriptor.
1927 @item ENOTSOCK
1928 The descriptor @var{socket} is not a socket.
1930 @item ENOTCONN
1931 The socket @var{socket} is not connected.
1933 @item ENOBUFS
1934 There are not enough internal buffers available.
1935 @end table
1936 @end deftypefun
1939 @node Transferring Data
1940 @subsection Transferring Data
1941 @cindex reading from a socket
1942 @cindex writing to a socket
1944 Once a socket has been connected to a peer, you can use the ordinary
1945 @code{read} and @code{write} operations (@pxref{I/O Primitives}) to
1946 transfer data.  A socket is a two-way communications channel, so read
1947 and write operations can be performed at either end.
1949 There are also some I/O modes that are specific to socket operations.
1950 In order to specify these modes, you must use the @code{recv} and
1951 @code{send} functions instead of the more generic @code{read} and
1952 @code{write} functions.  The @code{recv} and @code{send} functions take
1953 an additional argument which you can use to specify various flags to
1954 control the special I/O modes.  For example, you can specify the
1955 @code{MSG_OOB} flag to read or write out-of-band data, the
1956 @code{MSG_PEEK} flag to peek at input, or the @code{MSG_DONTROUTE} flag
1957 to control inclusion of routing information on output.
1959 @menu
1960 * Sending Data::                Sending data with @code{send}.
1961 * Receiving Data::              Reading data with @code{recv}.
1962 * Socket Data Options::         Using @code{send} and @code{recv}.
1963 @end menu
1965 @node Sending Data
1966 @subsubsection Sending Data
1968 @pindex sys/socket.h
1969 The @code{send} function is declared in the header file
1970 @file{sys/socket.h}.  If your @var{flags} argument is zero, you can just
1971 as well use @code{write} instead of @code{send}; see @ref{I/O
1972 Primitives}.  If the socket was connected but the connection has broken,
1973 you get a @code{SIGPIPE} signal for any use of @code{send} or
1974 @code{write} (@pxref{Miscellaneous Signals}).
1976 @comment sys/socket.h
1977 @comment BSD
1978 @deftypefun int send (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
1979 The @code{send} function is like @code{write}, but with the additional
1980 flags @var{flags}.  The possible values of @var{flags} are described
1981 in @ref{Socket Data Options}.
1983 This function returns the number of bytes transmitted, or @code{-1} on
1984 failure.  If the socket is nonblocking, then @code{send} (like
1985 @code{write}) can return after sending just part of the data.
1986 @xref{File Status Flags}, for information about nonblocking mode.
1988 Note, however, that a successful return value merely indicates that
1989 the message has been sent without error, not necessarily that it has
1990 been received without error.
1992 The following @code{errno} error conditions are defined for this function:
1994 @table @code
1995 @item EBADF
1996 The @var{socket} argument is not a valid file descriptor.
1998 @item EINTR
1999 The operation was interrupted by a signal before any data was sent.
2000 @xref{Interrupted Primitives}.
2002 @item ENOTSOCK
2003 The descriptor @var{socket} is not a socket.
2005 @item EMSGSIZE
2006 The socket type requires that the message be sent atomically, but the
2007 message is too large for this to be possible.
2009 @item EWOULDBLOCK
2010 Nonblocking mode has been set on the socket, and the write operation
2011 would block.  (Normally @code{send} blocks until the operation can be
2012 completed.)
2014 @item ENOBUFS
2015 There is not enough internal buffer space available.
2017 @item ENOTCONN
2018 You never connected this socket.
2020 @item EPIPE
2021 This socket was connected but the connection is now broken.  In this
2022 case, @code{send} generates a @code{SIGPIPE} signal first; if that
2023 signal is ignored or blocked, or if its handler returns, then
2024 @code{send} fails with @code{EPIPE}.
2025 @end table
2026 @end deftypefun
2028 @node Receiving Data
2029 @subsubsection Receiving Data
2031 @pindex sys/socket.h
2032 The @code{recv} function is declared in the header file
2033 @file{sys/socket.h}.  If your @var{flags} argument is zero, you can
2034 just as well use @code{read} instead of @code{recv}; see @ref{I/O
2035 Primitives}.
2037 @comment sys/socket.h
2038 @comment BSD
2039 @deftypefun int recv (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2040 The @code{recv} function is like @code{read}, but with the additional
2041 flags @var{flags}.  The possible values of @var{flags} are described
2042 In @ref{Socket Data Options}.
2044 If nonblocking mode is set for @var{socket}, and no data is available to
2045 be read, @code{recv} fails immediately rather than waiting.  @xref{File
2046 Status Flags}, for information about nonblocking mode.
2048 This function returns the number of bytes received, or @code{-1} on failure.
2049 The following @code{errno} error conditions are defined for this function:
2051 @table @code
2052 @item EBADF
2053 The @var{socket} argument is not a valid file descriptor.
2055 @item ENOTSOCK
2056 The descriptor @var{socket} is not a socket.
2058 @item EWOULDBLOCK
2059 Nonblocking mode has been set on the socket, and the read operation
2060 would block.  (Normally, @code{recv} blocks until there is input
2061 available to be read.)
2063 @item EINTR
2064 The operation was interrupted by a signal before any data was read.
2065 @xref{Interrupted Primitives}.
2067 @item ENOTCONN
2068 You never connected this socket.
2069 @end table
2070 @end deftypefun
2072 @node Socket Data Options
2073 @subsubsection Socket Data Options
2075 @pindex sys/socket.h
2076 The @var{flags} argument to @code{send} and @code{recv} is a bit
2077 mask.  You can bitwise-OR the values of the following macros together
2078 to obtain a value for this argument.  All are defined in the header
2079 file @file{sys/socket.h}.
2081 @comment sys/socket.h
2082 @comment BSD
2083 @deftypevr Macro int MSG_OOB
2084 Send or receive out-of-band data.  @xref{Out-of-Band Data}.
2085 @end deftypevr
2087 @comment sys/socket.h
2088 @comment BSD
2089 @deftypevr Macro int MSG_PEEK
2090 Look at the data but don't remove it from the input queue.  This is
2091 only meaningful with input functions such as @code{recv}, not with
2092 @code{send}.
2093 @end deftypevr
2095 @comment sys/socket.h
2096 @comment BSD
2097 @deftypevr Macro int MSG_DONTROUTE
2098 Don't include routing information in the message.  This is only
2099 meaningful with output operations, and is usually only of interest for
2100 diagnostic or routing programs.  We don't try to explain it here.
2101 @end deftypevr
2103 @node Byte Stream Example
2104 @subsection Byte Stream Socket Example
2106 Here is an example client program that makes a connection for a byte
2107 stream socket in the Internet namespace.  It doesn't do anything
2108 particularly interesting once it has connected to the server; it just
2109 sends a text string to the server and exits.
2111 @smallexample
2112 @include inetcli.c.texi
2113 @end smallexample
2115 @node Server Example
2116 @subsection Byte Stream Connection Server Example
2118 The server end is much more complicated.  Since we want to allow
2119 multiple clients to be connected to the server at the same time, it
2120 would be incorrect to wait for input from a single client by simply
2121 calling @code{read} or @code{recv}.  Instead, the right thing to do is
2122 to use @code{select} (@pxref{Waiting for I/O}) to wait for input on
2123 all of the open sockets.  This also allows the server to deal with
2124 additional connection requests.
2126 This particular server doesn't do anything interesting once it has
2127 gotten a message from a client.  It does close the socket for that
2128 client when it detects an end-of-file condition (resulting from the
2129 client shutting down its end of the connection).
2131 This program uses @code{make_socket} and @code{init_sockaddr} to set
2132 up the socket address; see @ref{Inet Example}.
2134 @smallexample
2135 @include inetsrv.c.texi
2136 @end smallexample
2138 @node Out-of-Band Data
2139 @subsection Out-of-Band Data
2141 @cindex out-of-band data
2142 @cindex high-priority data
2143 Streams with connections permit @dfn{out-of-band} data that is
2144 delivered with higher priority than ordinary data.  Typically the
2145 reason for sending out-of-band data is to send notice of an
2146 exceptional condition.  The way to send out-of-band data is using
2147 @code{send}, specifying the flag @code{MSG_OOB} (@pxref{Sending
2148 Data}).
2150 Out-of-band data is received with higher priority because the
2151 receiving process need not read it in sequence; to read the next
2152 available out-of-band data, use @code{recv} with the @code{MSG_OOB}
2153 flag (@pxref{Receiving Data}).  Ordinary read operations do not read
2154 out-of-band data; they read only the ordinary data.
2156 @cindex urgent socket condition
2157 When a socket finds that out-of-band data is on its way, it sends a
2158 @code{SIGURG} signal to the owner process or process group of the
2159 socket.  You can specify the owner using the @code{F_SETOWN} command
2160 to the @code{fcntl} function; see @ref{Interrupt Input}.  You must
2161 also establish a handler for this signal, as described in @ref{Signal
2162 Handling}, in order to take appropriate action such as reading the
2163 out-of-band data.
2165 Alternatively, you can test for pending out-of-band data, or wait
2166 until there is out-of-band data, using the @code{select} function; it
2167 can wait for an exceptional condition on the socket.  @xref{Waiting
2168 for I/O}, for more information about @code{select}.
2170 Notification of out-of-band data (whether with @code{SIGURG} or with
2171 @code{select}) indicates that out-of-band data is on the way; the data
2172 may not actually arrive until later.  If you try to read the
2173 out-of-band data before it arrives, @code{recv} fails with an
2174 @code{EWOULDBLOCK} error.
2176 Sending out-of-band data automatically places a ``mark'' in the stream
2177 of ordinary data, showing where in the sequence the out-of-band data
2178 ``would have been''.  This is useful when the meaning of out-of-band
2179 data is ``cancel everything sent so far''.  Here is how you can test,
2180 in the receiving process, whether any ordinary data was sent before
2181 the mark:
2183 @smallexample
2184 success = ioctl (socket, SIOCATMARK, &result);
2185 @end smallexample
2187 Here's a function to discard any ordinary data preceding the
2188 out-of-band mark:
2190 @smallexample
2192 discard_until_mark (int socket)
2194   while (1)
2195     @{
2196       /* @r{This is not an arbitrary limit; any size will do.}  */
2197       char buffer[1024];
2198       int result, success;
2200       /* @r{If we have reached the mark, return.}  */
2201       success = ioctl (socket, SIOCATMARK, &result);
2202       if (success < 0)
2203         perror ("ioctl");
2204       if (result)
2205         return;
2207       /* @r{Otherwise, read a bunch of ordinary data and discard it.}
2208          @r{This is guaranteed not to read past the mark}
2209          @r{if it starts before the mark.}  */
2210       success = read (socket, buffer, sizeof buffer);
2211       if (success < 0)
2212         perror ("read");
2213     @}
2215 @end smallexample
2217 If you don't want to discard the ordinary data preceding the mark, you
2218 may need to read some of it anyway, to make room in internal system
2219 buffers for the out-of-band data.  If you try to read out-of-band data
2220 and get an @code{EWOULDBLOCK} error, try reading some ordinary data
2221 (saving it so that you can use it when you want it) and see if that
2222 makes room.  Here is an example:
2224 @smallexample
2225 struct buffer
2227   char *buffer;
2228   int size;
2229   struct buffer *next;
2232 /* @r{Read the out-of-band data from SOCKET and return it}
2233    @r{as a `struct buffer', which records the address of the data}
2234    @r{and its size.}
2236    @r{It may be necessary to read some ordinary data}
2237    @r{in order to make room for the out-of-band data.}
2238    @r{If so, the ordinary data is saved as a chain of buffers}
2239    @r{found in the `next' field of the value.}  */
2241 struct buffer *
2242 read_oob (int socket)
2244   struct buffer *tail = 0;
2245   struct buffer *list = 0;
2247   while (1)
2248     @{
2249       /* @r{This is an arbitrary limit.}
2250          @r{Does anyone know how to do this without a limit?}  */
2251       char *buffer = (char *) xmalloc (1024);
2252       struct buffer *link;
2253       int success;
2254       int result;
2256       /* @r{Try again to read the out-of-band data.}  */
2257       success = recv (socket, buffer, sizeof buffer, MSG_OOB);
2258       if (success >= 0)
2259         @{
2260           /* @r{We got it, so return it.}  */
2261           struct buffer *link
2262             = (struct buffer *) xmalloc (sizeof (struct buffer));
2263           link->buffer = buffer;
2264           link->size = success;
2265           link->next = list;
2266           return link;
2267         @}
2269       /* @r{If we fail, see if we are at the mark.}  */
2270       success = ioctl (socket, SIOCATMARK, &result);
2271       if (success < 0)
2272         perror ("ioctl");
2273       if (result)
2274         @{
2275           /* @r{At the mark; skipping past more ordinary data cannot help.}
2276              @r{So just wait a while.}  */
2277           sleep (1);
2278           continue;
2279         @}
2281       /* @r{Otherwise, read a bunch of ordinary data and save it.}
2282          @r{This is guaranteed not to read past the mark}
2283          @r{if it starts before the mark.}  */
2284       success = read (socket, buffer, sizeof buffer);
2285       if (success < 0)
2286         perror ("read");
2288       /* @r{Save this data in the buffer list.}  */
2289       @{
2290         struct buffer *link
2291           = (struct buffer *) xmalloc (sizeof (struct buffer));
2292         link->buffer = buffer;
2293         link->size = success;
2295         /* @r{Add the new link to the end of the list.}  */
2296         if (tail)
2297           tail->next = link;
2298         else
2299           list = link;
2300         tail = link;
2301       @}
2302     @}
2304 @end smallexample
2306 @node Datagrams
2307 @section Datagram Socket Operations
2309 @cindex datagram socket
2310 This section describes how to use communication styles that don't use
2311 connections (styles @code{SOCK_DGRAM} and @code{SOCK_RDM}).  Using
2312 these styles, you group data into packets and each packet is an
2313 independent communication.  You specify the destination for each
2314 packet individually.
2316 Datagram packets are like letters: you send each one independently,
2317 with its own destination address, and they may arrive in the wrong
2318 order or not at all.
2320 The @code{listen} and @code{accept} functions are not allowed for
2321 sockets using connectionless communication styles.
2323 @menu
2324 * Sending Datagrams::    Sending packets on a datagram socket.
2325 * Receiving Datagrams::  Receiving packets on a datagram socket.
2326 * Datagram Example::     An example program: packets sent over a
2327                            datagram socket in the file namespace.
2328 * Example Receiver::     Another program, that receives those packets.
2329 @end menu
2331 @node Sending Datagrams
2332 @subsection Sending Datagrams
2333 @cindex sending a datagram
2334 @cindex transmitting datagrams
2335 @cindex datagrams, transmitting
2337 @pindex sys/socket.h
2338 The normal way of sending data on a datagram socket is by using the
2339 @code{sendto} function, declared in @file{sys/socket.h}.
2341 You can call @code{connect} on a datagram socket, but this only
2342 specifies a default destination for further data transmission on the
2343 socket.  When a socket has a default destination, then you can use
2344 @code{send} (@pxref{Sending Data}) or even @code{write} (@pxref{I/O
2345 Primitives}) to send a packet there.  You can cancel the default
2346 destination by calling @code{connect} using an address format of
2347 @code{AF_UNSPEC} in the @var{addr} argument.  @xref{Connecting}, for
2348 more information about the @code{connect} function.
2350 @comment sys/socket.h
2351 @comment BSD
2352 @deftypefun int sendto (int @var{socket}, void *@var{buffer}. size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, socklen_t @var{length})
2353 The @code{sendto} function transmits the data in the @var{buffer}
2354 through the socket @var{socket} to the destination address specified
2355 by the @var{addr} and @var{length} arguments.  The @var{size} argument
2356 specifies the number of bytes to be transmitted.
2358 The @var{flags} are interpreted the same way as for @code{send}; see
2359 @ref{Socket Data Options}.
2361 The return value and error conditions are also the same as for
2362 @code{send}, but you cannot rely on the system to detect errors and
2363 report them; the most common error is that the packet is lost or there
2364 is no one at the specified address to receive it, and the operating
2365 system on your machine usually does not know this.
2367 It is also possible for one call to @code{sendto} to report an error
2368 due to a problem related to a previous call.
2369 @end deftypefun
2371 @node Receiving Datagrams
2372 @subsection Receiving Datagrams
2373 @cindex receiving datagrams
2375 The @code{recvfrom} function reads a packet from a datagram socket and
2376 also tells you where it was sent from.  This function is declared in
2377 @file{sys/socket.h}.
2379 @comment sys/socket.h
2380 @comment BSD
2381 @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})
2382 The @code{recvfrom} function reads one packet from the socket
2383 @var{socket} into the buffer @var{buffer}.  The @var{size} argument
2384 specifies the maximum number of bytes to be read.
2386 If the packet is longer than @var{size} bytes, then you get the first
2387 @var{size} bytes of the packet, and the rest of the packet is lost.
2388 There's no way to read the rest of the packet.  Thus, when you use a
2389 packet protocol, you must always know how long a packet to expect.
2391 The @var{addr} and @var{length-ptr} arguments are used to return the
2392 address where the packet came from.  @xref{Socket Addresses}.  For a
2393 socket in the file domain, the address information won't be meaningful,
2394 since you can't read the address of such a socket (@pxref{File
2395 Namespace}).  You can specify a null pointer as the @var{addr} argument
2396 if you are not interested in this information.
2398 The @var{flags} are interpreted the same way as for @code{recv}
2399 (@pxref{Socket Data Options}).  The return value and error conditions
2400 are also the same as for @code{recv}.
2401 @end deftypefun
2403 You can use plain @code{recv} (@pxref{Receiving Data}) instead of
2404 @code{recvfrom} if you know don't need to find out who sent the packet
2405 (either because you know where it should come from or because you
2406 treat all possible senders alike).  Even @code{read} can be used if
2407 you don't want to specify @var{flags} (@pxref{I/O Primitives}).
2409 @ignore
2410 @c sendmsg and recvmsg are like readv and writev in that they
2411 @c use a series of buffers.  It's not clear this is worth
2412 @c supporting or that we support them.
2413 @c !!! they can do more; it is hairy
2415 @comment sys/socket.h
2416 @comment BSD
2417 @deftp {Data Type} {struct msghdr}
2418 @end deftp
2420 @comment sys/socket.h
2421 @comment BSD
2422 @deftypefun int sendmsg (int @var{socket}, const struct msghdr *@var{message}, int @var{flags})
2423 @end deftypefun
2425 @comment sys/socket.h
2426 @comment BSD
2427 @deftypefun int recvmsg (int @var{socket}, struct msghdr *@var{message}, int @var{flags})
2428 @end deftypefun
2429 @end ignore
2431 @node Datagram Example
2432 @subsection Datagram Socket Example
2434 Here is a set of example programs that send messages over a datagram
2435 stream in the file namespace.  Both the client and server programs use the
2436 @code{make_named_socket} function that was presented in @ref{File
2437 Namespace}, to create and name their sockets.
2439 First, here is the server program.  It sits in a loop waiting for
2440 messages to arrive, bouncing each message back to the sender.
2441 Obviously, this isn't a particularly useful program, but it does show
2442 the general ideas involved.
2444 @smallexample
2445 @include filesrv.c.texi
2446 @end smallexample
2448 @node Example Receiver
2449 @subsection Example of Reading Datagrams
2451 Here is the client program corresponding to the server above.
2453 It sends a datagram to the server and then waits for a reply.  Notice
2454 that the socket for the client (as well as for the server) in this
2455 example has to be given a name.  This is so that the server can direct
2456 a message back to the client.  Since the socket has no associated
2457 connection state, the only way the server can do this is by
2458 referencing the name of the client.
2460 @smallexample
2461 @include filecli.c.texi
2462 @end smallexample
2464 Keep in mind that datagram socket communications are unreliable.  In
2465 this example, the client program waits indefinitely if the message
2466 never reaches the server or if the server's response never comes
2467 back.  It's up to the user running the program to kill it and restart
2468 it, if desired.  A more automatic solution could be to use
2469 @code{select} (@pxref{Waiting for I/O}) to establish a timeout period
2470 for the reply, and in case of timeout either resend the message or
2471 shut down the socket and exit.
2473 @node Inetd
2474 @section The @code{inetd} Daemon
2476 We've explained above how to write a server program that does its own
2477 listening.  Such a server must already be running in order for anyone
2478 to connect to it.
2480 Another way to provide service for an Internet port is to let the daemon
2481 program @code{inetd} do the listening.  @code{inetd} is a program that
2482 runs all the time and waits (using @code{select}) for messages on a
2483 specified set of ports.  When it receives a message, it accepts the
2484 connection (if the socket style calls for connections) and then forks a
2485 child process to run the corresponding server program.  You specify the
2486 ports and their programs in the file @file{/etc/inetd.conf}.
2488 @menu
2489 * Inetd Servers::
2490 * Configuring Inetd::
2491 @end menu
2493 @node Inetd Servers
2494 @subsection @code{inetd} Servers
2496 Writing a server program to be run by @code{inetd} is very simple.  Each time
2497 someone requests a connection to the appropriate port, a new server
2498 process starts.  The connection already exists at this time; the
2499 socket is available as the standard input descriptor and as the
2500 standard output descriptor (descriptors 0 and 1) in the server
2501 process.  So the server program can begin reading and writing data
2502 right away.  Often the program needs only the ordinary I/O facilities;
2503 in fact, a general-purpose filter program that knows nothing about
2504 sockets can work as a byte stream server run by @code{inetd}.
2506 You can also use @code{inetd} for servers that use connectionless
2507 communication styles.  For these servers, @code{inetd} does not try to accept
2508 a connection, since no connection is possible.  It just starts the
2509 server program, which can read the incoming datagram packet from
2510 descriptor 0.  The server program can handle one request and then
2511 exit, or you can choose to write it to keep reading more requests
2512 until no more arrive, and then exit.  You must specify which of these
2513 two techniques the server uses, when you configure @code{inetd}.
2515 @node Configuring Inetd
2516 @subsection Configuring @code{inetd}
2518 The file @file{/etc/inetd.conf} tells @code{inetd} which ports to listen to
2519 and what server programs to run for them.  Normally each entry in the
2520 file is one line, but you can split it onto multiple lines provided
2521 all but the first line of the entry start with whitespace.  Lines that
2522 start with @samp{#} are comments.
2524 Here are two standard entries in @file{/etc/inetd.conf}:
2526 @smallexample
2527 ftp     stream  tcp     nowait  root    /libexec/ftpd   ftpd
2528 talk    dgram   udp     wait    root    /libexec/talkd  talkd
2529 @end smallexample
2531 An entry has this format:
2533 @smallexample
2534 @var{service} @var{style} @var{protocol} @var{wait} @var{username} @var{program} @var{arguments}
2535 @end smallexample
2537 The @var{service} field says which service this program provides.  It
2538 should be the name of a service defined in @file{/etc/services}.
2539 @code{inetd} uses @var{service} to decide which port to listen on for
2540 this entry.
2542 The fields @var{style} and @var{protocol} specify the communication
2543 style and the protocol to use for the listening socket.  The style
2544 should be the name of a communication style, converted to lower case
2545 and with @samp{SOCK_} deleted---for example, @samp{stream} or
2546 @samp{dgram}.  @var{protocol} should be one of the protocols listed in
2547 @file{/etc/protocols}.  The typical protocol names are @samp{tcp} for
2548 byte stream connections and @samp{udp} for unreliable datagrams.
2550 The @var{wait} field should be either @samp{wait} or @samp{nowait}.
2551 Use @samp{wait} if @var{style} is a connectionless style and the
2552 server, once started, handles multiple requests, as many as come in.
2553 Use @samp{nowait} if @code{inetd} should start a new process for each message
2554 or request that comes in.  If @var{style} uses connections, then
2555 @var{wait} @strong{must} be @samp{nowait}.
2557 @var{user} is the user name that the server should run as.  @code{inetd} runs
2558 as root, so it can set the user ID of its children arbitrarily.  It's
2559 best to avoid using @samp{root} for @var{user} if you can; but some
2560 servers, such as Telnet and FTP, read a username and password
2561 themselves.  These servers need to be root initially so they can log
2562 in as commanded by the data coming over the network.
2564 @var{program} together with @var{arguments} specifies the command to
2565 run to start the server.  @var{program} should be an absolute file
2566 name specifying the executable file to run.  @var{arguments} consists
2567 of any number of whitespace-separated words, which become the
2568 command-line arguments of @var{program}.  The first word in
2569 @var{arguments} is argument zero, which should by convention be the
2570 program name itself (sans directories).
2572 If you edit @file{/etc/inetd.conf}, you can tell @code{inetd} to reread the
2573 file and obey its new contents by sending the @code{inetd} process the
2574 @code{SIGHUP} signal.  You'll have to use @code{ps} to determine the
2575 process ID of the @code{inetd} process, as it is not fixed.
2577 @c !!! could document /etc/inetd.sec
2579 @node Socket Options
2580 @section Socket Options
2581 @cindex socket options
2583 This section describes how to read or set various options that modify
2584 the behavior of sockets and their underlying communications protocols.
2586 @cindex level, for socket options
2587 @cindex socket option level
2588 When you are manipulating a socket option, you must specify which
2589 @dfn{level} the option pertains to.  This describes whether the option
2590 applies to the socket interface, or to a lower-level communications
2591 protocol interface.
2593 @menu
2594 * Socket Option Functions::     The basic functions for setting and getting
2595                                  socket options.
2596 * Socket-Level Options::        Details of the options at the socket level.
2597 @end menu
2599 @node Socket Option Functions
2600 @subsection Socket Option Functions
2602 @pindex sys/socket.h
2603 Here are the functions for examining and modifying socket options.
2604 They are declared in @file{sys/socket.h}.
2606 @comment sys/socket.h
2607 @comment BSD
2608 @deftypefun int getsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t *@var{optlen-ptr})
2609 The @code{getsockopt} function gets information about the value of
2610 option @var{optname} at level @var{level} for socket @var{socket}.
2612 The option value is stored in a buffer that @var{optval} points to.
2613 Before the call, you should supply in @code{*@var{optlen-ptr}} the
2614 size of this buffer; on return, it contains the number of bytes of
2615 information actually stored in the buffer.
2617 Most options interpret the @var{optval} buffer as a single @code{int}
2618 value.
2620 The actual return value of @code{getsockopt} is @code{0} on success
2621 and @code{-1} on failure.  The following @code{errno} error conditions
2622 are defined:
2624 @table @code
2625 @item EBADF
2626 The @var{socket} argument is not a valid file descriptor.
2628 @item ENOTSOCK
2629 The descriptor @var{socket} is not a socket.
2631 @item ENOPROTOOPT
2632 The @var{optname} doesn't make sense for the given @var{level}.
2633 @end table
2634 @end deftypefun
2636 @comment sys/socket.h
2637 @comment BSD
2638 @deftypefun int setsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, socklen_t @var{optlen})
2639 This function is used to set the socket option @var{optname} at level
2640 @var{level} for socket @var{socket}.  The value of the option is passed
2641 in the buffer @var{optval}, which has size @var{optlen}.
2643 The return value and error codes for @code{setsockopt} are the same as
2644 for @code{getsockopt}.
2645 @end deftypefun
2647 @node Socket-Level Options
2648 @subsection Socket-Level Options
2650 @comment sys/socket.h
2651 @comment BSD
2652 @deftypevr Constant int SOL_SOCKET
2653 Use this constant as the @var{level} argument to @code{getsockopt} or
2654 @code{setsockopt} to manipulate the socket-level options described in
2655 this section.
2656 @end deftypevr
2658 @pindex sys/socket.h
2659 Here is a table of socket-level option names; all are defined in the
2660 header file @file{sys/socket.h}.
2662 @table @code
2663 @comment sys/socket.h
2664 @comment BSD
2665 @item SO_DEBUG
2666 @c Extra blank line here makes the table look better.
2668 This option toggles recording of debugging information in the underlying
2669 protocol modules.  The value has type @code{int}; a nonzero value means
2670 ``yes''.
2671 @c !!! should say how this is used
2672 @c Ok, anyone who knows, please explain.
2674 @comment sys/socket.h
2675 @comment BSD
2676 @item SO_REUSEADDR
2677 This option controls whether @code{bind} (@pxref{Setting Address})
2678 should permit reuse of local addresses for this socket.  If you enable
2679 this option, you can actually have two sockets with the same Internet
2680 port number; but the system won't allow you to use the two
2681 identically-named sockets in a way that would confuse the Internet.  The
2682 reason for this option is that some higher-level Internet protocols,
2683 including FTP, require you to keep reusing the same socket number.
2685 The value has type @code{int}; a nonzero value means ``yes''.
2687 @comment sys/socket.h
2688 @comment BSD
2689 @item SO_KEEPALIVE
2690 This option controls whether the underlying protocol should
2691 periodically transmit messages on a connected socket.  If the peer
2692 fails to respond to these messages, the connection is considered
2693 broken.  The value has type @code{int}; a nonzero value means
2694 ``yes''.
2696 @comment sys/socket.h
2697 @comment BSD
2698 @item SO_DONTROUTE
2699 This option controls whether outgoing messages bypass the normal
2700 message routing facilities.  If set, messages are sent directly to the
2701 network interface instead.  The value has type @code{int}; a nonzero
2702 value means ``yes''.
2704 @comment sys/socket.h
2705 @comment BSD
2706 @item SO_LINGER
2707 This option specifies what should happen when the socket of a type
2708 that promises reliable delivery still has untransmitted messages when
2709 it is closed; see @ref{Closing a Socket}.  The value has type
2710 @code{struct linger}.
2712 @comment sys/socket.h
2713 @comment BSD
2714 @deftp {Data Type} {struct linger}
2715 This structure type has the following members:
2717 @table @code
2718 @item int l_onoff
2719 This field is interpreted as a boolean.  If nonzero, @code{close}
2720 blocks until the data is transmitted or the timeout period has expired.
2722 @item int l_linger
2723 This specifies the timeout period, in seconds.
2724 @end table
2725 @end deftp
2727 @comment sys/socket.h
2728 @comment BSD
2729 @item SO_BROADCAST
2730 This option controls whether datagrams may be broadcast from the socket.
2731 The value has type @code{int}; a nonzero value means ``yes''.
2733 @comment sys/socket.h
2734 @comment BSD
2735 @item SO_OOBINLINE
2736 If this option is set, out-of-band data received on the socket is
2737 placed in the normal input queue.  This permits it to be read using
2738 @code{read} or @code{recv} without specifying the @code{MSG_OOB}
2739 flag.  @xref{Out-of-Band Data}.  The value has type @code{int}; a
2740 nonzero value means ``yes''.
2742 @comment sys/socket.h
2743 @comment BSD
2744 @item SO_SNDBUF
2745 This option gets or sets the size of the output buffer.  The value is a
2746 @code{size_t}, which is the size in bytes.
2748 @comment sys/socket.h
2749 @comment BSD
2750 @item SO_RCVBUF
2751 This option gets or sets the size of the input buffer.  The value is a
2752 @code{size_t}, which is the size in bytes.
2754 @comment sys/socket.h
2755 @comment GNU
2756 @item SO_STYLE
2757 @comment sys/socket.h
2758 @comment BSD
2759 @itemx SO_TYPE
2760 This option can be used with @code{getsockopt} only.  It is used to
2761 get the socket's communication style.  @code{SO_TYPE} is the
2762 historical name, and @code{SO_STYLE} is the preferred name in GNU.
2763 The value has type @code{int} and its value designates a communication
2764 style; see @ref{Communication Styles}.
2766 @comment sys/socket.h
2767 @comment BSD
2768 @item SO_ERROR
2769 @c Extra blank line here makes the table look better.
2771 This option can be used with @code{getsockopt} only.  It is used to reset
2772 the error status of the socket.  The value is an @code{int}, which represents
2773 the previous error status.
2774 @c !!! what is "socket error status"?  this is never defined.
2775 @end table
2777 @node Networks Database
2778 @section Networks Database
2779 @cindex networks database
2780 @cindex converting network number to network name
2781 @cindex converting network name to network number
2783 @pindex /etc/networks
2784 @pindex netdb.h
2785 Many systems come with a database that records a list of networks known
2786 to the system developer.  This is usually kept either in the file
2787 @file{/etc/networks} or in an equivalent from a name server.  This data
2788 base is useful for routing programs such as @code{route}, but it is not
2789 useful for programs that simply communicate over the network.  We
2790 provide functions to access this data base, which are declared in
2791 @file{netdb.h}.
2793 @comment netdb.h
2794 @comment BSD
2795 @deftp {Data Type} {struct netent}
2796 This data type is used to represent information about entries in the
2797 networks database.  It has the following members:
2799 @table @code
2800 @item char *n_name
2801 This is the ``official'' name of the network.
2803 @item char **n_aliases
2804 These are alternative names for the network, represented as a vector
2805 of strings.  A null pointer terminates the array.
2807 @item int n_addrtype
2808 This is the type of the network number; this is always equal to
2809 @code{AF_INET} for Internet networks.
2811 @item unsigned long int n_net
2812 This is the network number.  Network numbers are returned in host
2813 byte order; see @ref{Byte Order}.
2814 @end table
2815 @end deftp
2817 Use the @code{getnetbyname} or @code{getnetbyaddr} functions to search
2818 the networks database for information about a specific network.  The
2819 information is returned in a statically-allocated structure; you must
2820 copy the information if you need to save it.
2822 @comment netdb.h
2823 @comment BSD
2824 @deftypefun {struct netent *} getnetbyname (const char *@var{name})
2825 The @code{getnetbyname} function returns information about the network
2826 named @var{name}.  It returns a null pointer if there is no such
2827 network.
2828 @end deftypefun
2830 @comment netdb.h
2831 @comment BSD
2832 @deftypefun {struct netent *} getnetbyaddr (long @var{net}, int @var{type})
2833 The @code{getnetbyaddr} function returns information about the network
2834 of type @var{type} with number @var{net}.  You should specify a value of
2835 @code{AF_INET} for the @var{type} argument for Internet networks.
2837 @code{getnetbyaddr} returns a null pointer if there is no such
2838 network.
2839 @end deftypefun
2841 You can also scan the networks database using @code{setnetent},
2842 @code{getnetent}, and @code{endnetent}.  Be careful in using these
2843 functions, because they are not reentrant.
2845 @comment netdb.h
2846 @comment BSD
2847 @deftypefun void setnetent (int @var{stayopen})
2848 This function opens and rewinds the networks database.
2850 If the @var{stayopen} argument is nonzero, this sets a flag so that
2851 subsequent calls to @code{getnetbyname} or @code{getnetbyaddr} will
2852 not close the database (as they usually would).  This makes for more
2853 efficiency if you call those functions several times, by avoiding
2854 reopening the database for each call.
2855 @end deftypefun
2857 @comment netdb.h
2858 @comment BSD
2859 @deftypefun {struct netent *} getnetent (void)
2860 This function returns the next entry in the networks database.  It
2861 returns a null pointer if there are no more entries.
2862 @end deftypefun
2864 @comment netdb.h
2865 @comment BSD
2866 @deftypefun void endnetent (void)
2867 This function closes the networks database.
2868 @end deftypefun