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