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