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