1 @node Sockets, Low-Level Terminal Interface, Pipes and FIFOs, Top
4 This chapter describes the GNU facilities for interprocess
5 communication using sockets.
8 @cindex interprocess communication, with sockets
9 A @dfn{socket} is a generalized interprocess communication channel.
10 Like a pipe, a socket is represented as a file descriptor. But,
11 unlike pipes, sockets support communication between unrelated
12 processes, and even between processes running on different machines
13 that communicate over a network. Sockets are the primary means of
14 communicating with other machines; @code{telnet}, @code{rlogin},
15 @code{ftp}, @code{talk}, and the other familiar network programs use
18 Not all operating systems support sockets. In the GNU library, the
19 header file @file{sys/socket.h} exists regardless of the operating
20 system, and the socket functions always exist, but if the system does
21 not really support sockets, these functions always fail.
23 @strong{Incomplete:} We do not currently document the facilities for
24 broadcast messages or for configuring Internet interfaces.
27 * Socket Concepts:: Basic concepts you need to know about.
28 * Communication Styles::Stream communication, datagrams, and other styles.
29 * Socket Addresses:: How socket names (``addresses'') work.
30 * File Namespace:: Details about the file namespace.
31 * Internet Namespace:: Details about the Internet namespace.
32 * Misc Namespaces:: Other namespaces not documented fully here.
33 * Open/Close Sockets:: Creating sockets and destroying them.
34 * Connections:: Operations on sockets with connection state.
35 * Datagrams:: Operations on datagram sockets.
36 * Inetd:: Inetd is a daemon that starts servers on request.
37 The most convenient way to write a server
38 is to make it work with Inetd.
39 * Socket Options:: Miscellaneous low-level socket options.
40 * Networks Database:: Accessing the database of network names.
44 @section Socket Concepts
46 @cindex communication style (of a socket)
47 @cindex style of communication (of a socket)
48 When you create a socket, you must specify the style of communication
49 you want to use and the type of protocol that should implement it.
50 The @dfn{communication style} of a socket defines the user-level
51 semantics of sending and receiving data on the socket. Choosing a
52 communication style specifies the answers to questions such as these:
58 @cindex stream (sockets)
59 @strong{What are the units of data transmission?} Some communication
60 styles regard the data as a sequence of bytes, with no larger
61 structure; others group the bytes into records (which are known in
62 this context as @dfn{packets}).
65 @cindex loss of data on sockets
66 @cindex data loss on sockets
67 @strong{Can data be lost during normal operation?} Some communication
68 styles guarantee that all the data sent arrives in the order it was
69 sent (barring system or network crashes); other styles occasionally
70 lose data as a normal part of operation, and may sometimes deliver
71 packets more than once or in the wrong order.
73 Designing a program to use unreliable communication styles usually
74 involves taking precautions to detect lost or misordered packets and
75 to retransmit data as needed.
78 @strong{Is communication entirely with one partner?} Some
79 communication styles are like a telephone call---you make a
80 @dfn{connection} with one remote socket, and then exchange data
81 freely. Other styles are like mailing letters---you specify a
82 destination address for each message you send.
85 @cindex namespace (of socket)
86 @cindex domain (of socket)
87 @cindex socket namespace
89 You must also choose a @dfn{namespace} for naming the socket. A socket
90 name (``address'') is meaningful only in the context of a particular
91 namespace. In fact, even the data type to use for a socket name may
92 depend on the namespace. Namespaces are also called ``domains'', but we
93 avoid that word as it can be confused with other usage of the same
94 term. Each namespace has a symbolic name that starts with @samp{PF_}.
95 A corresponding symbolic name starting with @samp{AF_} designates the
96 address format for that namespace.
98 @cindex network protocol
99 @cindex protocol (of socket)
100 @cindex socket protocol
101 @cindex protocol family
102 Finally you must choose the @dfn{protocol} to carry out the
103 communication. The protocol determines what low-level mechanism is used
104 to transmit and receive data. Each protocol is valid for a particular
105 namespace and communication style; a namespace is sometimes called a
106 @dfn{protocol family} because of this, which is why the namespace names
107 start with @samp{PF_}.
109 The rules of a protocol apply to the data passing between two programs,
110 perhaps on different computers; most of these rules are handled by the
111 operating system, and you need not know about them. What you do need to
112 know about protocols is this:
116 In order to have communication between two sockets, they must specify
117 the @emph{same} protocol.
120 Each protocol is meaningful with particular style/namespace
121 combinations and cannot be used with inappropriate combinations. For
122 example, the TCP protocol fits only the byte stream style of
123 communication and the Internet namespace.
126 For each combination of style and namespace, there is a @dfn{default
127 protocol} which you can request by specifying 0 as the protocol
128 number. And that's what you should normally do---use the default.
131 @node Communication Styles
132 @section Communication Styles
134 The GNU library includes support for several different kinds of sockets,
135 each with different characteristics. This section describes the
136 supported socket types. The symbolic constants listed here are
137 defined in @file{sys/socket.h}.
140 @comment sys/socket.h
142 @deftypevr Macro int SOCK_STREAM
143 The @code{SOCK_STREAM} style is like a pipe (@pxref{Pipes and FIFOs});
144 it operates over a connection with a particular remote socket, and
145 transmits data reliably as a stream of bytes.
147 Use of this style is covered in detail in @ref{Connections}.
150 @comment sys/socket.h
152 @deftypevr Macro int SOCK_DGRAM
153 The @code{SOCK_DGRAM} style is used for sending
154 individually-addressed packets, unreliably.
155 It is the diametrical opposite of @code{SOCK_STREAM}.
157 Each time you write data to a socket of this kind, that data becomes
158 one packet. Since @code{SOCK_DGRAM} sockets do not have connections,
159 you must specify the recipient address with each packet.
161 The only guarantee that the system makes about your requests to
162 transmit data is that it will try its best to deliver each packet you
163 send. It may succeed with the sixth packet after failing with the
164 fourth and fifth packets; the seventh packet may arrive before the
165 sixth, and may arrive a second time after the sixth.
167 The typical use for @code{SOCK_DGRAM} is in situations where it is
168 acceptable to simply resend a packet if no response is seen in a
169 reasonable amount of time.
171 @xref{Datagrams}, for detailed information about how to use datagram
176 @c This appears to be only for the NS domain, which we aren't
177 @c discussing and probably won't support either.
178 @comment sys/socket.h
180 @deftypevr Macro int SOCK_SEQPACKET
181 This style is like @code{SOCK_STREAM} except that the data is
182 structured into packets.
184 A program that receives data over a @code{SOCK_SEQPACKET} socket
185 should be prepared to read the entire message packet in a single call
186 to @code{read}; if it only reads part of the message, the remainder of
187 the message is simply discarded instead of being available for
188 subsequent calls to @code{read}.
190 Many protocols do not support this communication style.
195 @comment sys/socket.h
197 @deftypevr Macro int SOCK_RDM
198 This style is a reliable version of @code{SOCK_DGRAM}: it sends
199 individually addressed packets, but guarantees that each packet sent
200 arrives exactly once.
202 @strong{Warning:} It is not clear this is actually supported
203 by any operating system.
207 @comment sys/socket.h
209 @deftypevr Macro int SOCK_RAW
210 This style provides access to low-level network protocols and
211 interfaces. Ordinary user programs usually have no need to use this
215 @node Socket Addresses
216 @section Socket Addresses
218 @cindex address of socket
219 @cindex name of socket
220 @cindex binding a socket address
221 @cindex socket address (name) binding
222 The name of a socket is normally called an @dfn{address}. The
223 functions and symbols for dealing with socket addresses were named
224 inconsistently, sometimes using the term ``name'' and sometimes using
225 ``address''. You can regard these terms as synonymous where sockets
228 A socket newly created with the @code{socket} function has no
229 address. Other processes can find it for communication only if you
230 give it an address. We call this @dfn{binding} the address to the
231 socket, and the way to do it is with the @code{bind} function.
233 You need be concerned with the address of a socket if other processes
234 are to find it and start communicating with it. You can specify an
235 address for other sockets, but this is usually pointless; the first time
236 you send data from a socket, or use it to initiate a connection, the
237 system assigns an address automatically if you have not specified one.
239 Occasionally a client needs to specify an address because the server
240 discriminates based on addresses; for example, the rsh and rlogin
241 protocols look at the client's socket address and don't bypass password
242 checking unless it is less than @code{IPPORT_RESERVED} (@pxref{Ports}).
244 The details of socket addresses vary depending on what namespace you are
245 using. @xref{File Namespace}, or @ref{Internet Namespace}, for specific
248 Regardless of the namespace, you use the same functions @code{bind} and
249 @code{getsockname} to set and examine a socket's address. These
250 functions use a phony data type, @code{struct sockaddr *}, to accept the
251 address. In practice, the address lives in a structure of some other
252 data type appropriate to the address format you are using, but you cast
253 its address to @code{struct sockaddr *} when you pass it to
257 * Address Formats:: About @code{struct sockaddr}.
258 * Setting Address:: Binding an address to a socket.
259 * Reading Address:: Reading the address of a socket.
262 @node Address Formats
263 @subsection Address Formats
265 The functions @code{bind} and @code{getsockname} use the generic data
266 type @code{struct sockaddr *} to represent a pointer to a socket
267 address. You can't use this data type effectively to interpret an
268 address or construct one; for that, you must use the proper data type
269 for the socket's namespace.
271 Thus, the usual practice is to construct an address in the proper
272 namespace-specific type, then cast a pointer to @code{struct sockaddr *}
273 when you call @code{bind} or @code{getsockname}.
275 The one piece of information that you can get from the @code{struct
276 sockaddr} data type is the @dfn{address format} designator which tells
277 you which data type to use to understand the address fully.
280 The symbols in this section are defined in the header file
283 @comment sys/socket.h
285 @deftp {Date Type} {struct sockaddr}
286 The @code{struct sockaddr} type itself has the following members:
289 @item short int sa_family
290 This is the code for the address format of this address. It
291 identifies the format of the data which follows.
293 @item char sa_data[14]
294 This is the actual socket address data, which is format-dependent. Its
295 length also depends on the format, and may well be more than 14. The
296 length 14 of @code{sa_data} is essentially arbitrary.
300 Each address format has a symbolic name which starts with @samp{AF_}.
301 Each of them corresponds to a @samp{PF_} symbol which designates the
302 corresponding namespace. Here is a list of address format names:
305 @comment sys/socket.h
309 This designates the address format that goes with the file namespace.
310 (@code{PF_FILE} is the name of that namespace.) @xref{File Namespace
311 Details}, for information about this address format.
313 @comment sys/socket.h
317 This is a synonym for @code{AF_FILE}, for compatibility.
318 (@code{PF_UNIX} is likewise a synonym for @code{PF_FILE}.)
320 @comment sys/socket.h
324 This designates the address format that goes with the Internet
325 namespace. (@code{PF_INET} is the name of that namespace.)
326 @xref{Internet Address Formats}.
328 @comment sys/socket.h
329 @comment IPv6 Basic API
331 This is similar to @code{AF_INET}, but refers to the IPv6 protocol.
332 (@code{PF_INET6} is the name of the corresponding namespace.)
334 @comment sys/socket.h
338 This designates no particular address format. It is used only in rare
339 cases, such as to clear out the default destination address of a
340 ``connected'' datagram socket. @xref{Sending Datagrams}.
342 The corresponding namespace designator symbol @code{PF_UNSPEC} exists
343 for completeness, but there is no reason to use it in a program.
346 @file{sys/socket.h} defines symbols starting with @samp{AF_} for many
347 different kinds of networks, all or most of which are not actually
348 implemented. We will document those that really work, as we receive
349 information about how to use them.
351 @node Setting Address
352 @subsection Setting the Address of a Socket
355 Use the @code{bind} function to assign an address to a socket. The
356 prototype for @code{bind} is in the header file @file{sys/socket.h}.
357 For examples of use, see @ref{File Namespace}, or see @ref{Inet Example}.
359 @comment sys/socket.h
361 @deftypefun int bind (int @var{socket}, struct sockaddr *@var{addr}, size_t @var{length})
362 The @code{bind} function assigns an address to the socket
363 @var{socket}. The @var{addr} and @var{length} arguments specify the
364 address; the detailed format of the address depends on the namespace.
365 The first part of the address is always the format designator, which
366 specifies a namespace, and says that the address is in the format for
369 The return value is @code{0} on success and @code{-1} on failure. The
370 following @code{errno} error conditions are defined for this function:
374 The @var{socket} argument is not a valid file descriptor.
377 The descriptor @var{socket} is not a socket.
380 The specified address is not available on this machine.
383 Some other socket is already using the specified address.
386 The socket @var{socket} already has an address.
389 You do not have permission to access the requested address. (In the
390 Internet domain, only the super-user is allowed to specify a port number
391 in the range 0 through @code{IPPORT_RESERVED} minus one; see
395 Additional conditions may be possible depending on the particular namespace
399 @node Reading Address
400 @subsection Reading the Address of a Socket
403 Use the function @code{getsockname} to examine the address of an
404 Internet socket. The prototype for this function is in the header file
407 @comment sys/socket.h
409 @deftypefun int getsockname (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
410 The @code{getsockname} function returns information about the
411 address of the socket @var{socket} in the locations specified by the
412 @var{addr} and @var{length-ptr} arguments. Note that the
413 @var{length-ptr} is a pointer; you should initialize it to be the
414 allocation size of @var{addr}, and on return it contains the actual
415 size of the address data.
417 The format of the address data depends on the socket namespace. The
418 length of the information is usually fixed for a given namespace, so
419 normally you can know exactly how much space is needed and can provide
420 that much. The usual practice is to allocate a place for the value
421 using the proper data type for the socket's namespace, then cast its
422 address to @code{struct sockaddr *} to pass it to @code{getsockname}.
424 The return value is @code{0} on success and @code{-1} on error. The
425 following @code{errno} error conditions are defined for this function:
429 The @var{socket} argument is not a valid file descriptor.
432 The descriptor @var{socket} is not a socket.
435 There are not enough internal buffers available for the operation.
439 You can't read the address of a socket in the file namespace. This is
440 consistent with the rest of the system; in general, there's no way to
441 find a file's name from a descriptor for that file.
444 @section The File Namespace
445 @cindex file namespace, for sockets
447 This section describes the details of the file namespace, whose
448 symbolic name (required when you create a socket) is @code{PF_FILE}.
451 * Concepts: File Namespace Concepts. What you need to understand.
452 * Details: File Namespace Details. Address format, symbolic names, etc.
453 * Example: File Socket Example. Example of creating a socket.
456 @node File Namespace Concepts
457 @subsection File Namespace Concepts
459 In the file namespace, socket addresses are file names. You can specify
460 any file name you want as the address of the socket, but you must have
461 write permission on the directory containing it. In order to connect to
462 a socket, you must have read permission for it. It's common to put
463 these files in the @file{/tmp} directory.
465 One peculiarity of the file namespace is that the name is only used when
466 opening the connection; once that is over with, the address is not
467 meaningful and may not exist.
469 Another peculiarity is that you cannot connect to such a socket from
470 another machine--not even if the other machine shares the file system
471 which contains the name of the socket. You can see the socket in a
472 directory listing, but connecting to it never succeeds. Some programs
473 take advantage of this, such as by asking the client to send its own
474 process ID, and using the process IDs to distinguish between clients.
475 However, we recommend you not use this method in protocols you design,
476 as we might someday permit connections from other machines that mount
477 the same file systems. Instead, send each new client an identifying
478 number if you want it to have one.
480 After you close a socket in the file namespace, you should delete the
481 file name from the file system. Use @code{unlink} or @code{remove} to
482 do this; see @ref{Deleting Files}.
484 The file namespace supports just one protocol for any communication
485 style; it is protocol number @code{0}.
487 @node File Namespace Details
488 @subsection Details of File Namespace
491 To create a socket in the file namespace, use the constant
492 @code{PF_FILE} as the @var{namespace} argument to @code{socket} or
493 @code{socketpair}. This constant is defined in @file{sys/socket.h}.
495 @comment sys/socket.h
497 @deftypevr Macro int PF_FILE
498 This designates the file namespace, in which socket addresses are file
499 names, and its associated family of protocols.
502 @comment sys/socket.h
504 @deftypevr Macro int PF_UNIX
505 This is a synonym for @code{PF_FILE}, for compatibility's sake.
508 The structure for specifying socket names in the file namespace is
509 defined in the header file @file{sys/un.h}:
514 @deftp {Data Type} {struct sockaddr_un}
515 This structure is used to specify file namespace socket addresses. It has
516 the following members:
519 @item short int sun_family
520 This identifies the address family or format of the socket address.
521 You should store the value @code{AF_FILE} to designate the file
522 namespace. @xref{Socket Addresses}.
524 @item char sun_path[108]
525 This is the file name to use.
527 @strong{Incomplete:} Why is 108 a magic number? RMS suggests making
528 this a zero-length array and tweaking the example following to use
529 @code{alloca} to allocate an appropriate amount of storage based on
530 the length of the filename.
534 You should compute the @var{length} parameter for a socket address in
535 the file namespace as the sum of the size of the @code{sun_family}
536 component and the string length (@emph{not} the allocation size!) of
537 the file name string.
539 @node File Socket Example
540 @subsection Example of File-Namespace Sockets
542 Here is an example showing how to create and name a socket in the file
546 @include mkfsock.c.texi
549 @node Internet Namespace
550 @section The Internet Namespace
551 @cindex Internet namespace, for sockets
553 This section describes the details the protocols and socket naming
554 conventions used in the Internet namespace.
556 To create a socket in the Internet namespace, use the symbolic name
557 @code{PF_INET} of this namespace as the @var{namespace} argument to
558 @code{socket} or @code{socketpair}. This macro is defined in
562 @comment sys/socket.h
564 @deftypevr Macro int PF_INET
565 This designates the Internet namespace and associated family of
569 A socket address for the Internet namespace includes the following components:
573 The address of the machine you want to connect to. Internet addresses
574 can be specified in several ways; these are discussed in @ref{Internet
575 Address Formats}, @ref{Host Addresses}, and @ref{Host Names}.
578 A port number for that machine. @xref{Ports}.
581 You must ensure that the address and port number are represented in a
582 canonical format called @dfn{network byte order}. @xref{Byte Order},
583 for information about this.
586 * Internet Address Formats:: How socket addresses are specified in the
588 * Host Addresses:: All about host addresses of internet host.
589 * Protocols Database:: Referring to protocols by name.
590 * Ports:: Internet port numbers.
591 * Services Database:: Ports may have symbolic names.
592 * Byte Order:: Different hosts may use different byte
593 ordering conventions; you need to
594 canonicalize host address and port number.
595 * Inet Example:: Putting it all together.
598 @node Internet Address Formats
599 @subsection Internet Socket Address Formats
601 In the Internet namespace, for both IPv4 (@code{AF_INET}) and IPv6
602 (@code{AF_INET6}), a socket address consists of a host address
603 and a port on that host. In addition, the protocol you choose serves
604 effectively as a part of the address because local port numbers are
605 meaningful only within a particular protocol.
607 The data types for representing socket addresses in the Internet namespace
608 are defined in the header file @file{netinet/in.h}.
611 @comment netinet/in.h
613 @deftp {Data Type} {struct sockaddr_in}
614 This is the data type used to represent socket addresses in the
615 Internet namespace. It has the following members:
618 @item short int sin_family
619 This identifies the address family or format of the socket address.
620 You should store the value of @code{AF_INET} in this member.
621 @xref{Socket Addresses}.
623 @item struct in_addr sin_addr
624 This is the Internet address of the host machine. @xref{Host
625 Addresses}, and @ref{Host Names}, for how to get a value to store
628 @item unsigned short int sin_port
629 This is the port number. @xref{Ports}.
633 When you call @code{bind} or @code{getsockname}, you should specify
634 @code{sizeof (struct sockaddr_in)} as the @var{length} parameter if
635 you are using an Internet namespace socket address.
637 @deftp {Data Type} {struct sockaddr_in6}
638 This is the data type used to represent socket addresses in the IPv6
639 namespace. It has the following members:
642 @item short int sin6_family
643 This identifies the address family or format of the socket address.
644 You should store the value of @code{AF_INET6} in this member.
645 @xref{Socket Addresses}.
647 @item struct in6_addr sin6_addr
648 This is the IPv6 address of the host machine. @xref{Host
649 Addresses}, and @ref{Host Names}, for how to get a value to store
652 @item uint32_t sin6_flowinfo
653 This is a currently unimplemented field.
655 @item uint16_t sin6_port
656 This is the port number. @xref{Ports}.
662 @subsection Host Addresses
664 Each computer on the Internet has one or more @dfn{Internet addresses},
665 numbers which identify that computer among all those on the Internet.
666 Users typically write IPv4 numeric host addresses as sequences of four
667 numbers, separated by periods, as in @samp{128.52.46.32}, and IPv6
668 numeric host addresses as sequences of up to eight numbers seperated by
669 colons, as in @samp{5f03:1200:836f:c100::1}.
671 Each computer also has one or more @dfn{host names}, which are strings
672 of words separated by periods, as in @samp{churchy.gnu.ai.mit.edu}.
674 Programs that let the user specify a host typically accept both numeric
675 addresses and host names. But the program needs a numeric address to
676 open a connection; to use a host name, you must convert it to the
677 numeric address it stands for.
680 * Abstract Host Addresses:: What a host number consists of.
681 * Data type: Host Address Data Type. Data type for a host number.
682 * Functions: Host Address Functions. Functions to operate on them.
683 * Names: Host Names. Translating host names to host numbers.
686 @node Abstract Host Addresses
687 @subsubsection Internet Host Addresses
688 @cindex host address, Internet
689 @cindex Internet host address
692 Each computer on the Internet has one or more Internet addresses,
693 numbers which identify that computer among all those on the Internet.
696 @c I think this whole section could possibly be removed. It is slightly
697 @c misleading these days.
699 @cindex network number
700 @cindex local network address number
701 An Internet host address is a number containing four bytes of data.
702 These are divided into two parts, a @dfn{network number} and a
703 @dfn{local network address number} within that network. The network
704 number consists of the first one, two or three bytes; the rest of the
705 bytes are the local address.
707 Network numbers are registered with the Network Information Center
708 (NIC), and are divided into three classes---A, B, and C. The local
709 network address numbers of individual machines are registered with the
710 administrator of the particular network.
712 Class A networks have single-byte numbers in the range 0 to 127. There
713 are only a small number of Class A networks, but they can each support a
714 very large number of hosts. Medium-sized Class B networks have two-byte
715 network numbers, with the first byte in the range 128 to 191. Class C
716 networks are the smallest; they have three-byte network numbers, with
717 the first byte in the range 192-255. Thus, the first 1, 2, or 3 bytes
718 of an Internet address specifies a network. The remaining bytes of the
719 Internet address specify the address within that network.
721 The Class A network 0 is reserved for broadcast to all networks. In
722 addition, the host number 0 within each network is reserved for broadcast
723 to all hosts in that network.
725 The Class A network 127 is reserved for loopback; you can always use
726 the Internet address @samp{127.0.0.1} to refer to the host machine.
728 Since a single machine can be a member of multiple networks, it can
729 have multiple Internet host addresses. However, there is never
730 supposed to be more than one machine with the same host address.
732 @c !!! this section could document the IN_CLASS* macros in <netinet/in.h>.
734 @cindex standard dot notation, for Internet addresses
735 @cindex dot notation, for Internet addresses
736 There are four forms of the @dfn{standard numbers-and-dots notation}
737 for Internet addresses:
740 @item @var{a}.@var{b}.@var{c}.@var{d}
741 This specifies all four bytes of the address individually.
743 @item @var{a}.@var{b}.@var{c}
744 The last part of the address, @var{c}, is interpreted as a 2-byte quantity.
745 This is useful for specifying host addresses in a Class B network with
746 network address number @code{@var{a}.@var{b}}.
748 @item @var{a}.@var{b}
749 The last part of the address, @var{c}, is interpreted as a 3-byte quantity.
750 This is useful for specifying host addresses in a Class A network with
751 network address number @var{a}.
754 If only one part is given, this corresponds directly to the host address
758 Within each part of the address, the usual C conventions for specifying
759 the radix apply. In other words, a leading @samp{0x} or @samp{0X} implies
760 hexadecimal radix; a leading @samp{0} implies octal; and otherwise decimal
763 @node Host Address Data Type
764 @subsubsection Host Address Data Type
766 Internet host addresses are represented in some contexts as integers
767 (type @code{unsigned long int}). In other contexts, the integer is
768 packaged inside a structure of type @code{struct in_addr}. It would
769 be better if the usage were made consistent, but it is not hard to extract
770 the integer from the structure or put the integer into a structure.
772 The following basic definitions for Internet addresses appear in the
773 header file @file{netinet/in.h}:
776 @comment netinet/in.h
778 @deftp {Data Type} {struct in_addr}
779 This data type is used in certain contexts to contain an Internet host
780 address. It has just one field, named @code{s_addr}, which records the
781 host address number as an @code{unsigned long int}.
784 @comment netinet/in.h
786 @deftypevr Macro {unsigned int} INADDR_LOOPBACK
787 You can use this constant to stand for ``the address of this machine,''
788 instead of finding its actual address. It is the Internet address
789 @samp{127.0.0.1}, which is usually called @samp{localhost}. This
790 special constant saves you the trouble of looking up the address of your
791 own machine. Also, the system usually implements @code{INADDR_LOOPBACK}
792 specially, avoiding any network traffic for the case of one machine
796 @comment netinet/in.h
798 @deftypevr Macro {unsigned int} INADDR_ANY
799 You can use this constant to stand for ``any incoming address,'' when
800 binding to an address. @xref{Setting Address}. This is the usual
801 address to give in the @code{sin_addr} member of @w{@code{struct
802 sockaddr_in}} when you want to accept Internet connections.
805 @comment netinet/in.h
807 @deftypevr Macro {unsigned int} INADDR_BROADCAST
808 This constant is the address you use to send a broadcast message.
809 @c !!! broadcast needs further documented
812 @comment netinet/in.h
814 @deftypevr Macro {unsigned int} INADDR_NONE
815 This constant is returned by some functions to indicate an error.
818 @comment netinet/in.h
819 @comment IPv6 basic API
820 @deftp {Data Type} {struct in6_addr}
821 This data type is used to store an IPv6 address. It stores 128 bits of
822 data, which can be accessed (via a union) in a variety of ways.
825 @comment netinet/in.h
826 @comment IPv6 basic API
827 @deftypevr Constant {struct in6_addr} in6addr_loopback.
828 This constant is the IPv6 address @samp{::1}, the loopback address. See
829 above for a description of what this means. The macro
830 @code{IN6ADDR_LOOPBACK_INIT} is provided to allow you to initialise your
831 own variables to this value.
834 @comment netinet/in.h
835 @comment IPv6 basic API
836 @deftypevr Constant {struct in6_addr} in6addr_any
837 This constant is the IPv6 address @samp{::}, the unspecified address. See
838 above for a description of what this means. The macro
839 @code{IN6ADDR_ANY_INIT} is provided to allow you to initialise your
840 own variables to this value.
843 @node Host Address Functions
844 @subsubsection Host Address Functions
847 These additional functions for manipulating Internet addresses are
848 declared in @file{arpa/inet.h}. They represent Internet addresses in
849 network byte order; they represent network numbers and
850 local-address-within-network numbers in host byte order.
851 @xref{Byte Order}, for an explanation of network and host byte order.
855 @deftypefun int inet_aton (const char *@var{name}, struct in_addr *@var{addr})
856 This function converts the Internet host address @var{name}
857 from the standard numbers-and-dots notation into binary data and stores
858 it in the @code{struct in_addr} that @var{addr} points to.
859 @code{inet_aton} returns nonzero if the address is valid, zero if not.
864 @deftypefun {unsigned long int} inet_addr (const char *@var{name})
865 This function converts the Internet host address @var{name} from the
866 standard numbers-and-dots notation into binary data. If the input is
867 not valid, @code{inet_addr} returns @code{INADDR_NONE}. This is an
868 obsolete interface to @code{inet_aton}, described immediately above; it
869 is obsolete because @code{INADDR_NONE} is a valid address
870 (255.255.255.255), and @code{inet_aton} provides a cleaner way to
871 indicate error return.
876 @deftypefun {unsigned long int} inet_network (const char *@var{name})
877 This function extracts the network number from the address @var{name},
878 given in the standard numbers-and-dots notation.
879 If the input is not valid, @code{inet_network} returns @code{-1}.
884 @deftypefun {char *} inet_ntoa (struct in_addr @var{addr})
885 This function converts the Internet host address @var{addr} to a
886 string in the standard numbers-and-dots notation. The return value is
887 a pointer into a statically-allocated buffer. Subsequent calls will
888 overwrite the same buffer, so you should copy the string if you need
891 In multi-threaded programs each thread has an own statically-allocated
892 buffer. But still subsequent calls of @code{inet_ntoa} in the same
893 thread will overwrite the result of the last call.
898 @deftypefun {struct in_addr} inet_makeaddr (int @var{net}, int @var{local})
899 This function makes an Internet host address by combining the network
900 number @var{net} with the local-address-within-network number
906 @deftypefun int inet_lnaof (struct in_addr @var{addr})
907 This function returns the local-address-within-network part of the
908 Internet host address @var{addr}.
913 @deftypefun int inet_netof (struct in_addr @var{addr})
914 This function returns the network number part of the Internet host
919 @comment IPv6 basic API
920 @deftypefun int inet_pton (int @var{af}, const char *@var{cp}, void *@var{buf})
921 This function converts an Internet address (either IPv4 or IPv6) from
922 presentation (textual) to network (binary) format. @var{af} should be
923 either @code{AF_INET} or @code{AF_INET6}, as appropriate for the type of
924 address being converted. @var{cp} is a pointer to the input string, and
925 @var{buf} is a pointer to a buffer for the result. It is the caller's
926 responsibility to make sure the buffer is large enough.
930 @comment IPv6 basic API
931 @deftypefun {char *} inet_ntop (int @var{af}, const void *@var{cp}, char *@var{buf}, size_t @var{len})
932 This function converts an Internet address (either IPv4 or IPv6) from
933 network (binary) to presentation (textual) form. @var{af} should be
934 either @code{AF_INET} or @code{AF_INET6}, as appropriate. @var{cp} is a
935 pointer to the address to be converted. @var{buf} should be a pointer
936 to a buffer to hold the result, and @var{len} is the length of this
937 buffer. The return value from the function will be this buffer address.
941 @subsubsection Host Names
942 @cindex hosts database
943 @cindex converting host name to address
944 @cindex converting host address to name
946 Besides the standard numbers-and-dots notation for Internet addresses,
947 you can also refer to a host by a symbolic name. The advantage of a
948 symbolic name is that it is usually easier to remember. For example,
949 the machine with Internet address @samp{128.52.46.32} is also known as
950 @samp{churchy.gnu.ai.mit.edu}; and other machines in the @samp{gnu.ai.mit.edu}
951 domain can refer to it simply as @samp{churchy}.
955 Internally, the system uses a database to keep track of the mapping
956 between host names and host numbers. This database is usually either
957 the file @file{/etc/hosts} or an equivalent provided by a name server.
958 The functions and other symbols for accessing this database are declared
959 in @file{netdb.h}. They are BSD features, defined unconditionally if
960 you include @file{netdb.h}.
964 @deftp {Data Type} {struct hostent}
965 This data type is used to represent an entry in the hosts database. It
966 has the following members:
970 This is the ``official'' name of the host.
972 @item char **h_aliases
973 These are alternative names for the host, represented as a null-terminated
977 This is the host address type; in practice, its value is always either
978 @code{AF_INET} or @code{AF_INET6}, with the latter being used for IPv6
979 hosts. In principle other kinds of addresses could be represented in
980 the data base as well as Internet addresses; if this were done, you
981 might find a value in this field other than @code{AF_INET} or
982 @code{AF_INET6}. @xref{Socket Addresses}.
985 This is the length, in bytes, of each address.
987 @item char **h_addr_list
988 This is the vector of addresses for the host. (Recall that the host
989 might be connected to multiple networks and have different addresses on
990 each one.) The vector is terminated by a null pointer.
993 This is a synonym for @code{h_addr_list[0]}; in other words, it is the
998 As far as the host database is concerned, each address is just a block
999 of memory @code{h_length} bytes long. But in other contexts there is an
1000 implicit assumption that you can convert this to a @code{struct in_addr} or
1001 an @code{unsigned long int}. Host addresses in a @code{struct hostent}
1002 structure are always given in network byte order; see @ref{Byte Order}.
1004 You can use @code{gethostbyname}, @code{gethostbyname2} or
1005 @code{gethostbyaddr} to search the hosts database for information about
1006 a particular host. The information is returned in a
1007 statically-allocated structure; you must copy the information if you
1008 need to save it across calls. You can also use @code{getaddrinfo} and
1009 @code{getnameinfo} to obtain this information.
1013 @deftypefun {struct hostent *} gethostbyname (const char *@var{name})
1014 The @code{gethostbyname} function returns information about the host
1015 named @var{name}. If the lookup fails, it returns a null pointer.
1019 @comment IPv6 Basic API
1020 @deftypefun {struct hostent *} gethostbyname2 (const char *@var{name}, int @var{af})
1021 The @code{gethostbyname2} function is like @code{gethostbyname}, but
1022 allows the caller to specify the desired address family (e.g.@:
1023 @code{AF_INET} or @code{AF_INET6}) for the result.
1028 @deftypefun {struct hostent *} gethostbyaddr (const char *@var{addr}, int @var{length}, int @var{format})
1029 The @code{gethostbyaddr} function returns information about the host
1030 with Internet address @var{addr}. The @var{length} argument is the
1031 size (in bytes) of the address at @var{addr}. @var{format} specifies
1032 the address format; for an Internet address, specify a value of
1035 If the lookup fails, @code{gethostbyaddr} returns a null pointer.
1039 If the name lookup by @code{gethostbyname} or @code{gethostbyaddr}
1040 fails, you can find out the reason by looking at the value of the
1041 variable @code{h_errno}. (It would be cleaner design for these
1042 functions to set @code{errno}, but use of @code{h_errno} is compatible
1043 with other systems.) Before using @code{h_errno}, you must declare it
1050 Here are the error codes that you may find in @code{h_errno}:
1055 @item HOST_NOT_FOUND
1056 @vindex HOST_NOT_FOUND
1057 No such host is known in the data base.
1063 This condition happens when the name server could not be contacted. If
1064 you try again later, you may succeed then.
1070 A non-recoverable error occurred.
1076 The host database contains an entry for the name, but it doesn't have an
1077 associated Internet address.
1080 You can also scan the entire hosts database one entry at a time using
1081 @code{sethostent}, @code{gethostent}, and @code{endhostent}. Be careful
1082 in using these functions, because they are not reentrant.
1086 @deftypefun void sethostent (int @var{stayopen})
1087 This function opens the hosts database to begin scanning it. You can
1088 then call @code{gethostent} to read the entries.
1090 @c There was a rumor that this flag has different meaning if using the DNS,
1091 @c but it appears this description is accurate in that case also.
1092 If the @var{stayopen} argument is nonzero, this sets a flag so that
1093 subsequent calls to @code{gethostbyname} or @code{gethostbyaddr} will
1094 not close the database (as they usually would). This makes for more
1095 efficiency if you call those functions several times, by avoiding
1096 reopening the database for each call.
1101 @deftypefun {struct hostent *} gethostent ()
1102 This function returns the next entry in the hosts database. It
1103 returns a null pointer if there are no more entries.
1108 @deftypefun void endhostent ()
1109 This function closes the hosts database.
1113 @subsection Internet Ports
1116 A socket address in the Internet namespace consists of a machine's
1117 Internet address plus a @dfn{port number} which distinguishes the
1118 sockets on a given machine (for a given protocol). Port numbers range
1121 Port numbers less than @code{IPPORT_RESERVED} are reserved for standard
1122 servers, such as @code{finger} and @code{telnet}. There is a database
1123 that keeps track of these, and you can use the @code{getservbyname}
1124 function to map a service name onto a port number; see @ref{Services
1127 If you write a server that is not one of the standard ones defined in
1128 the database, you must choose a port number for it. Use a number
1129 greater than @code{IPPORT_USERRESERVED}; such numbers are reserved for
1130 servers and won't ever be generated automatically by the system.
1131 Avoiding conflicts with servers being run by other users is up to you.
1133 When you use a socket without specifying its address, the system
1134 generates a port number for it. This number is between
1135 @code{IPPORT_RESERVED} and @code{IPPORT_USERRESERVED}.
1137 On the Internet, it is actually legitimate to have two different
1138 sockets with the same port number, as long as they never both try to
1139 communicate with the same socket address (host address plus port
1140 number). You shouldn't duplicate a port number except in special
1141 circumstances where a higher-level protocol requires it. Normally,
1142 the system won't let you do it; @code{bind} normally insists on
1143 distinct port numbers. To reuse a port number, you must set the
1144 socket option @code{SO_REUSEADDR}. @xref{Socket-Level Options}.
1146 @pindex netinet/in.h
1147 These macros are defined in the header file @file{netinet/in.h}.
1149 @comment netinet/in.h
1151 @deftypevr Macro int IPPORT_RESERVED
1152 Port numbers less than @code{IPPORT_RESERVED} are reserved for
1156 @comment netinet/in.h
1158 @deftypevr Macro int IPPORT_USERRESERVED
1159 Port numbers greater than or equal to @code{IPPORT_USERRESERVED} are
1160 reserved for explicit use; they will never be allocated automatically.
1163 @node Services Database
1164 @subsection The Services Database
1165 @cindex services database
1166 @cindex converting service name to port number
1167 @cindex converting port number to service name
1169 @pindex /etc/services
1170 The database that keeps track of ``well-known'' services is usually
1171 either the file @file{/etc/services} or an equivalent from a name server.
1172 You can use these utilities, declared in @file{netdb.h}, to access
1173 the services database.
1178 @deftp {Data Type} {struct servent}
1179 This data type holds information about entries from the services database.
1180 It has the following members:
1184 This is the ``official'' name of the service.
1186 @item char **s_aliases
1187 These are alternate names for the service, represented as an array of
1188 strings. A null pointer terminates the array.
1191 This is the port number for the service. Port numbers are given in
1192 network byte order; see @ref{Byte Order}.
1195 This is the name of the protocol to use with this service.
1196 @xref{Protocols Database}.
1200 To get information about a particular service, use the
1201 @code{getservbyname} or @code{getservbyport} functions. The information
1202 is returned in a statically-allocated structure; you must copy the
1203 information if you need to save it across calls.
1207 @deftypefun {struct servent *} getservbyname (const char *@var{name}, const char *@var{proto})
1208 The @code{getservbyname} function returns information about the
1209 service named @var{name} using protocol @var{proto}. If it can't find
1210 such a service, it returns a null pointer.
1212 This function is useful for servers as well as for clients; servers
1213 use it to determine which port they should listen on (@pxref{Listening}).
1218 @deftypefun {struct servent *} getservbyport (int @var{port}, const char *@var{proto})
1219 The @code{getservbyport} function returns information about the
1220 service at port @var{port} using protocol @var{proto}. If it can't
1221 find such a service, it returns a null pointer.
1224 You can also scan the services database using @code{setservent},
1225 @code{getservent}, and @code{endservent}. Be careful in using these
1226 functions, because they are not reentrant.
1230 @deftypefun void setservent (int @var{stayopen})
1231 This function opens the services database to begin scanning it.
1233 If the @var{stayopen} argument is nonzero, this sets a flag so that
1234 subsequent calls to @code{getservbyname} or @code{getservbyport} will
1235 not close the database (as they usually would). This makes for more
1236 efficiency if you call those functions several times, by avoiding
1237 reopening the database for each call.
1242 @deftypefun {struct servent *} getservent (void)
1243 This function returns the next entry in the services database. If
1244 there are no more entries, it returns a null pointer.
1249 @deftypefun void endservent (void)
1250 This function closes the services database.
1254 @subsection Byte Order Conversion
1255 @cindex byte order conversion, for socket
1256 @cindex converting byte order
1259 @cindex little-endian
1260 Different kinds of computers use different conventions for the
1261 ordering of bytes within a word. Some computers put the most
1262 significant byte within a word first (this is called ``big-endian''
1263 order), and others put it last (``little-endian'' order).
1265 @cindex network byte order
1266 So that machines with different byte order conventions can
1267 communicate, the Internet protocols specify a canonical byte order
1268 convention for data transmitted over the network. This is known
1269 as the @dfn{network byte order}.
1271 When establishing an Internet socket connection, you must make sure that
1272 the data in the @code{sin_port} and @code{sin_addr} members of the
1273 @code{sockaddr_in} structure are represented in the network byte order.
1274 If you are encoding integer data in the messages sent through the
1275 socket, you should convert this to network byte order too. If you don't
1276 do this, your program may fail when running on or talking to other kinds
1279 If you use @code{getservbyname} and @code{gethostbyname} or
1280 @code{inet_addr} to get the port number and host address, the values are
1281 already in the network byte order, and you can copy them directly into
1282 the @code{sockaddr_in} structure.
1284 Otherwise, you have to convert the values explicitly. Use
1285 @code{htons} and @code{ntohs} to convert values for the @code{sin_port}
1286 member. Use @code{htonl} and @code{ntohl} to convert values for the
1287 @code{sin_addr} member. (Remember, @code{struct in_addr} is equivalent
1288 to @code{unsigned long int}.) These functions are declared in
1289 @file{netinet/in.h}.
1290 @pindex netinet/in.h
1292 @comment netinet/in.h
1294 @deftypefun {unsigned short int} htons (unsigned short int @var{hostshort})
1295 This function converts the @code{short} integer @var{hostshort} from
1296 host byte order to network byte order.
1299 @comment netinet/in.h
1301 @deftypefun {unsigned short int} ntohs (unsigned short int @var{netshort})
1302 This function converts the @code{short} integer @var{netshort} from
1303 network byte order to host byte order.
1306 @comment netinet/in.h
1308 @deftypefun {unsigned long int} htonl (unsigned long int @var{hostlong})
1309 This function converts the @code{long} integer @var{hostlong} from
1310 host byte order to network byte order.
1313 @comment netinet/in.h
1315 @deftypefun {unsigned long int} ntohl (unsigned long int @var{netlong})
1316 This function converts the @code{long} integer @var{netlong} from
1317 network byte order to host byte order.
1320 @node Protocols Database
1321 @subsection Protocols Database
1322 @cindex protocols database
1324 The communications protocol used with a socket controls low-level
1325 details of how data is exchanged. For example, the protocol implements
1326 things like checksums to detect errors in transmissions, and routing
1327 instructions for messages. Normal user programs have little reason to
1328 mess with these details directly.
1330 @cindex TCP (Internet protocol)
1331 The default communications protocol for the Internet namespace depends on
1332 the communication style. For stream communication, the default is TCP
1333 (``transmission control protocol''). For datagram communication, the
1334 default is UDP (``user datagram protocol''). For reliable datagram
1335 communication, the default is RDP (``reliable datagram protocol'').
1336 You should nearly always use the default.
1338 @pindex /etc/protocols
1339 Internet protocols are generally specified by a name instead of a
1340 number. The network protocols that a host knows about are stored in a
1341 database. This is usually either derived from the file
1342 @file{/etc/protocols}, or it may be an equivalent provided by a name
1343 server. You look up the protocol number associated with a named
1344 protocol in the database using the @code{getprotobyname} function.
1346 Here are detailed descriptions of the utilities for accessing the
1347 protocols database. These are declared in @file{netdb.h}.
1352 @deftp {Data Type} {struct protoent}
1353 This data type is used to represent entries in the network protocols
1354 database. It has the following members:
1358 This is the official name of the protocol.
1360 @item char **p_aliases
1361 These are alternate names for the protocol, specified as an array of
1362 strings. The last element of the array is a null pointer.
1365 This is the protocol number (in host byte order); use this member as the
1366 @var{protocol} argument to @code{socket}.
1370 You can use @code{getprotobyname} and @code{getprotobynumber} to search
1371 the protocols database for a specific protocol. The information is
1372 returned in a statically-allocated structure; you must copy the
1373 information if you need to save it across calls.
1377 @deftypefun {struct protoent *} getprotobyname (const char *@var{name})
1378 The @code{getprotobyname} function returns information about the
1379 network protocol named @var{name}. If there is no such protocol, it
1380 returns a null pointer.
1385 @deftypefun {struct protoent *} getprotobynumber (int @var{protocol})
1386 The @code{getprotobynumber} function returns information about the
1387 network protocol with number @var{protocol}. If there is no such
1388 protocol, it returns a null pointer.
1391 You can also scan the whole protocols database one protocol at a time by
1392 using @code{setprotoent}, @code{getprotoent}, and @code{endprotoent}.
1393 Be careful in using these functions, because they are not reentrant.
1397 @deftypefun void setprotoent (int @var{stayopen})
1398 This function opens the protocols database to begin scanning it.
1400 If the @var{stayopen} argument is nonzero, this sets a flag so that
1401 subsequent calls to @code{getprotobyname} or @code{getprotobynumber} will
1402 not close the database (as they usually would). This makes for more
1403 efficiency if you call those functions several times, by avoiding
1404 reopening the database for each call.
1409 @deftypefun {struct protoent *} getprotoent (void)
1410 This function returns the next entry in the protocols database. It
1411 returns a null pointer if there are no more entries.
1416 @deftypefun void endprotoent (void)
1417 This function closes the protocols database.
1421 @subsection Internet Socket Example
1423 Here is an example showing how to create and name a socket in the
1424 Internet namespace. The newly created socket exists on the machine that
1425 the program is running on. Rather than finding and using the machine's
1426 Internet address, this example specifies @code{INADDR_ANY} as the host
1427 address; the system replaces that with the machine's actual address.
1430 @include mkisock.c.texi
1433 Here is another example, showing how you can fill in a @code{sockaddr_in}
1434 structure, given a host name string and a port number:
1437 @include isockad.c.texi
1440 @node Misc Namespaces
1441 @section Other Namespaces
1448 Certain other namespaces and associated protocol families are supported
1449 but not documented yet because they are not often used. @code{PF_NS}
1450 refers to the Xerox Network Software protocols. @code{PF_ISO} stands
1451 for Open Systems Interconnect. @code{PF_CCITT} refers to protocols from
1452 CCITT. @file{socket.h} defines these symbols and others naming protocols
1453 not actually implemented.
1455 @code{PF_IMPLINK} is used for communicating between hosts and Internet
1456 Message Processors. For information on this, and on @code{PF_ROUTE}, an
1457 occasionally-used local area routing protocol, see the GNU Hurd Manual
1458 (to appear in the future).
1460 @node Open/Close Sockets
1461 @section Opening and Closing Sockets
1463 This section describes the actual library functions for opening and
1464 closing sockets. The same functions work for all namespaces and
1468 * Creating a Socket:: How to open a socket.
1469 * Closing a Socket:: How to close a socket.
1470 * Socket Pairs:: These are created like pipes.
1473 @node Creating a Socket
1474 @subsection Creating a Socket
1475 @cindex creating a socket
1476 @cindex socket, creating
1477 @cindex opening a socket
1479 The primitive for creating a socket is the @code{socket} function,
1480 declared in @file{sys/socket.h}.
1481 @pindex sys/socket.h
1483 @comment sys/socket.h
1485 @deftypefun int socket (int @var{namespace}, int @var{style}, int @var{protocol})
1486 This function creates a socket and specifies communication style
1487 @var{style}, which should be one of the socket styles listed in
1488 @ref{Communication Styles}. The @var{namespace} argument specifies
1489 the namespace; it must be @code{PF_FILE} (@pxref{File Namespace}) or
1490 @code{PF_INET} (@pxref{Internet Namespace}). @var{protocol}
1491 designates the specific protocol (@pxref{Socket Concepts}); zero is
1492 usually right for @var{protocol}.
1494 The return value from @code{socket} is the file descriptor for the new
1495 socket, or @code{-1} in case of error. The following @code{errno} error
1496 conditions are defined for this function:
1499 @item EPROTONOSUPPORT
1500 The @var{protocol} or @var{style} is not supported by the
1501 @var{namespace} specified.
1504 The process already has too many file descriptors open.
1507 The system already has too many file descriptors open.
1510 The process does not have privilege to create a socket of the specified
1511 @var{style} or @var{protocol}.
1514 The system ran out of internal buffer space.
1517 The file descriptor returned by the @code{socket} function supports both
1518 read and write operations. But, like pipes, sockets do not support file
1519 positioning operations.
1522 For examples of how to call the @code{socket} function,
1523 see @ref{File Namespace}, or @ref{Inet Example}.
1526 @node Closing a Socket
1527 @subsection Closing a Socket
1528 @cindex socket, closing
1529 @cindex closing a socket
1530 @cindex shutting down a socket
1531 @cindex socket shutdown
1533 When you are finished using a socket, you can simply close its
1534 file descriptor with @code{close}; see @ref{Opening and Closing Files}.
1535 If there is still data waiting to be transmitted over the connection,
1536 normally @code{close} tries to complete this transmission. You
1537 can control this behavior using the @code{SO_LINGER} socket option to
1538 specify a timeout period; see @ref{Socket Options}.
1540 @pindex sys/socket.h
1541 You can also shut down only reception or only transmission on a
1542 connection by calling @code{shutdown}, which is declared in
1543 @file{sys/socket.h}.
1545 @comment sys/socket.h
1547 @deftypefun int shutdown (int @var{socket}, int @var{how})
1548 The @code{shutdown} function shuts down the connection of socket
1549 @var{socket}. The argument @var{how} specifies what action to
1554 Stop receiving data for this socket. If further data arrives,
1558 Stop trying to transmit data from this socket. Discard any data
1559 waiting to be sent. Stop looking for acknowledgement of data already
1560 sent; don't retransmit it if it is lost.
1563 Stop both reception and transmission.
1566 The return value is @code{0} on success and @code{-1} on failure. The
1567 following @code{errno} error conditions are defined for this function:
1571 @var{socket} is not a valid file descriptor.
1574 @var{socket} is not a socket.
1577 @var{socket} is not connected.
1582 @subsection Socket Pairs
1583 @cindex creating a socket pair
1585 @cindex opening a socket pair
1587 @pindex sys/socket.h
1588 A @dfn{socket pair} consists of a pair of connected (but unnamed)
1589 sockets. It is very similar to a pipe and is used in much the same
1590 way. Socket pairs are created with the @code{socketpair} function,
1591 declared in @file{sys/socket.h}. A socket pair is much like a pipe; the
1592 main difference is that the socket pair is bidirectional, whereas the
1593 pipe has one input-only end and one output-only end (@pxref{Pipes and
1596 @comment sys/socket.h
1598 @deftypefun int socketpair (int @var{namespace}, int @var{style}, int @var{protocol}, int @var{filedes}@t{[2]})
1599 This function creates a socket pair, returning the file descriptors in
1600 @code{@var{filedes}[0]} and @code{@var{filedes}[1]}. The socket pair
1601 is a full-duplex communications channel, so that both reading and writing
1602 may be performed at either end.
1604 The @var{namespace}, @var{style}, and @var{protocol} arguments are
1605 interpreted as for the @code{socket} function. @var{style} should be
1606 one of the communication styles listed in @ref{Communication Styles}.
1607 The @var{namespace} argument specifies the namespace, which must be
1608 @code{AF_FILE} (@pxref{File Namespace}); @var{protocol} specifies the
1609 communications protocol, but zero is the only meaningful value.
1611 If @var{style} specifies a connectionless communication style, then
1612 the two sockets you get are not @emph{connected}, strictly speaking,
1613 but each of them knows the other as the default destination address,
1614 so they can send packets to each other.
1616 The @code{socketpair} function returns @code{0} on success and @code{-1}
1617 on failure. The following @code{errno} error conditions are defined
1622 The process has too many file descriptors open.
1625 The specified namespace is not supported.
1627 @item EPROTONOSUPPORT
1628 The specified protocol is not supported.
1631 The specified protocol does not support the creation of socket pairs.
1636 @section Using Sockets with Connections
1641 The most common communication styles involve making a connection to a
1642 particular other socket, and then exchanging data with that socket
1643 over and over. Making a connection is asymmetric; one side (the
1644 @dfn{client}) acts to request a connection, while the other side (the
1645 @dfn{server}) makes a socket and waits for the connection request.
1650 @ref{Connecting}, describes what the client program must do to
1651 initiate a connection with a server.
1654 @ref{Listening}, and @ref{Accepting Connections}, describe what the
1655 server program must do to wait for and act upon connection requests
1659 @ref{Transferring Data}, describes how data is transferred through the
1665 * Connecting:: What the client program must do.
1666 * Listening:: How a server program waits for requests.
1667 * Accepting Connections:: What the server does when it gets a request.
1668 * Who is Connected:: Getting the address of the
1669 other side of a connection.
1670 * Transferring Data:: How to send and receive data.
1671 * Byte Stream Example:: An example program: a client for communicating
1672 over a byte stream socket in the Internet namespace.
1673 * Server Example:: A corresponding server program.
1674 * Out-of-Band Data:: This is an advanced feature.
1678 @subsection Making a Connection
1679 @cindex connecting a socket
1680 @cindex socket, connecting
1681 @cindex socket, initiating a connection
1682 @cindex socket, client actions
1684 In making a connection, the client makes a connection while the server
1685 waits for and accepts the connection. Here we discuss what the client
1686 program must do, using the @code{connect} function, which is declared in
1687 @file{sys/socket.h}.
1689 @comment sys/socket.h
1691 @deftypefun int connect (int @var{socket}, struct sockaddr *@var{addr}, size_t @var{length})
1692 The @code{connect} function initiates a connection from the socket
1693 with file descriptor @var{socket} to the socket whose address is
1694 specified by the @var{addr} and @var{length} arguments. (This socket
1695 is typically on another machine, and it must be already set up as a
1696 server.) @xref{Socket Addresses}, for information about how these
1697 arguments are interpreted.
1699 Normally, @code{connect} waits until the server responds to the request
1700 before it returns. You can set nonblocking mode on the socket
1701 @var{socket} to make @code{connect} return immediately without waiting
1702 for the response. @xref{File Status Flags}, for information about
1704 @c !!! how do you tell when it has finished connecting? I suspect the
1705 @c way you do it is select for writing.
1707 The normal return value from @code{connect} is @code{0}. If an error
1708 occurs, @code{connect} returns @code{-1}. The following @code{errno}
1709 error conditions are defined for this function:
1713 The socket @var{socket} is not a valid file descriptor.
1716 File descriptor @var{socket} is not a socket.
1719 The specified address is not available on the remote machine.
1722 The namespace of the @var{addr} is not supported by this socket.
1725 The socket @var{socket} is already connected.
1728 The attempt to establish the connection timed out.
1731 The server has actively refused to establish the connection.
1734 The network of the given @var{addr} isn't reachable from this host.
1737 The socket address of the given @var{addr} is already in use.
1740 The socket @var{socket} is non-blocking and the connection could not be
1741 established immediately. You can determine when the connection is
1742 completely established with @code{select}; @pxref{Waiting for I/O}.
1743 Another @code{connect} call on the same socket, before the connection is
1744 completely established, will fail with @code{EALREADY}.
1747 The socket @var{socket} is non-blocking and already has a pending
1748 connection in progress (see @code{EINPROGRESS} above).
1753 @subsection Listening for Connections
1754 @cindex listening (sockets)
1755 @cindex sockets, server actions
1756 @cindex sockets, listening
1758 Now let us consider what the server process must do to accept
1759 connections on a socket. First it must use the @code{listen} function
1760 to enable connection requests on the socket, and then accept each
1761 incoming connection with a call to @code{accept} (@pxref{Accepting
1762 Connections}). Once connection requests are enabled on a server socket,
1763 the @code{select} function reports when the socket has a connection
1764 ready to be accepted (@pxref{Waiting for I/O}).
1766 The @code{listen} function is not allowed for sockets using
1767 connectionless communication styles.
1769 You can write a network server that does not even start running until a
1770 connection to it is requested. @xref{Inetd Servers}.
1772 In the Internet namespace, there are no special protection mechanisms
1773 for controlling access to connect to a port; any process on any machine
1774 can make a connection to your server. If you want to restrict access to
1775 your server, make it examine the addresses associated with connection
1776 requests or implement some other handshaking or identification
1779 In the File namespace, the ordinary file protection bits control who has
1780 access to connect to the socket.
1782 @comment sys/socket.h
1784 @deftypefun int listen (int @var{socket}, unsigned int @var{n})
1785 The @code{listen} function enables the socket @var{socket} to accept
1786 connections, thus making it a server socket.
1788 The argument @var{n} specifies the length of the queue for pending
1789 connections. When the queue fills, new clients attempting to connect
1790 fail with @code{ECONNREFUSED} until the server calls @code{accept} to
1791 accept a connection from the queue.
1793 The @code{listen} function returns @code{0} on success and @code{-1}
1794 on failure. The following @code{errno} error conditions are defined
1799 The argument @var{socket} is not a valid file descriptor.
1802 The argument @var{socket} is not a socket.
1805 The socket @var{socket} does not support this operation.
1809 @node Accepting Connections
1810 @subsection Accepting Connections
1811 @cindex sockets, accepting connections
1812 @cindex accepting connections
1814 When a server receives a connection request, it can complete the
1815 connection by accepting the request. Use the function @code{accept}
1818 A socket that has been established as a server can accept connection
1819 requests from multiple clients. The server's original socket
1820 @emph{does not become part} of the connection; instead, @code{accept}
1821 makes a new socket which participates in the connection.
1822 @code{accept} returns the descriptor for this socket. The server's
1823 original socket remains available for listening for further connection
1826 The number of pending connection requests on a server socket is finite.
1827 If connection requests arrive from clients faster than the server can
1828 act upon them, the queue can fill up and additional requests are refused
1829 with a @code{ECONNREFUSED} error. You can specify the maximum length of
1830 this queue as an argument to the @code{listen} function, although the
1831 system may also impose its own internal limit on the length of this
1834 @comment sys/socket.h
1836 @deftypefun int accept (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
1837 This function is used to accept a connection request on the server
1838 socket @var{socket}.
1840 The @code{accept} function waits if there are no connections pending,
1841 unless the socket @var{socket} has nonblocking mode set. (You can use
1842 @code{select} to wait for a pending connection, with a nonblocking
1843 socket.) @xref{File Status Flags}, for information about nonblocking
1846 The @var{addr} and @var{length-ptr} arguments are used to return
1847 information about the name of the client socket that initiated the
1848 connection. @xref{Socket Addresses}, for information about the format
1851 Accepting a connection does not make @var{socket} part of the
1852 connection. Instead, it creates a new socket which becomes
1853 connected. The normal return value of @code{accept} is the file
1854 descriptor for the new socket.
1856 After @code{accept}, the original socket @var{socket} remains open and
1857 unconnected, and continues listening until you close it. You can
1858 accept further connections with @var{socket} by calling @code{accept}
1861 If an error occurs, @code{accept} returns @code{-1}. The following
1862 @code{errno} error conditions are defined for this function:
1866 The @var{socket} argument is not a valid file descriptor.
1869 The descriptor @var{socket} argument is not a socket.
1872 The descriptor @var{socket} does not support this operation.
1875 @var{socket} has nonblocking mode set, and there are no pending
1876 connections immediately available.
1880 The @code{accept} function is not allowed for sockets using
1881 connectionless communication styles.
1883 @node Who is Connected
1884 @subsection Who is Connected to Me?
1886 @comment sys/socket.h
1888 @deftypefun int getpeername (int @var{socket}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
1889 The @code{getpeername} function returns the address of the socket that
1890 @var{socket} is connected to; it stores the address in the memory space
1891 specified by @var{addr} and @var{length-ptr}. It stores the length of
1892 the address in @code{*@var{length-ptr}}.
1894 @xref{Socket Addresses}, for information about the format of the
1895 address. In some operating systems, @code{getpeername} works only for
1896 sockets in the Internet domain.
1898 The return value is @code{0} on success and @code{-1} on error. The
1899 following @code{errno} error conditions are defined for this function:
1903 The argument @var{socket} is not a valid file descriptor.
1906 The descriptor @var{socket} is not a socket.
1909 The socket @var{socket} is not connected.
1912 There are not enough internal buffers available.
1917 @node Transferring Data
1918 @subsection Transferring Data
1919 @cindex reading from a socket
1920 @cindex writing to a socket
1922 Once a socket has been connected to a peer, you can use the ordinary
1923 @code{read} and @code{write} operations (@pxref{I/O Primitives}) to
1924 transfer data. A socket is a two-way communications channel, so read
1925 and write operations can be performed at either end.
1927 There are also some I/O modes that are specific to socket operations.
1928 In order to specify these modes, you must use the @code{recv} and
1929 @code{send} functions instead of the more generic @code{read} and
1930 @code{write} functions. The @code{recv} and @code{send} functions take
1931 an additional argument which you can use to specify various flags to
1932 control the special I/O modes. For example, you can specify the
1933 @code{MSG_OOB} flag to read or write out-of-band data, the
1934 @code{MSG_PEEK} flag to peek at input, or the @code{MSG_DONTROUTE} flag
1935 to control inclusion of routing information on output.
1938 * Sending Data:: Sending data with @code{send}.
1939 * Receiving Data:: Reading data with @code{recv}.
1940 * Socket Data Options:: Using @code{send} and @code{recv}.
1944 @subsubsection Sending Data
1946 @pindex sys/socket.h
1947 The @code{send} function is declared in the header file
1948 @file{sys/socket.h}. If your @var{flags} argument is zero, you can just
1949 as well use @code{write} instead of @code{send}; see @ref{I/O
1950 Primitives}. If the socket was connected but the connection has broken,
1951 you get a @code{SIGPIPE} signal for any use of @code{send} or
1952 @code{write} (@pxref{Miscellaneous Signals}).
1954 @comment sys/socket.h
1956 @deftypefun int send (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
1957 The @code{send} function is like @code{write}, but with the additional
1958 flags @var{flags}. The possible values of @var{flags} are described
1959 in @ref{Socket Data Options}.
1961 This function returns the number of bytes transmitted, or @code{-1} on
1962 failure. If the socket is nonblocking, then @code{send} (like
1963 @code{write}) can return after sending just part of the data.
1964 @xref{File Status Flags}, for information about nonblocking mode.
1966 Note, however, that a successful return value merely indicates that
1967 the message has been sent without error, not necessarily that it has
1968 been received without error.
1970 The following @code{errno} error conditions are defined for this function:
1974 The @var{socket} argument is not a valid file descriptor.
1977 The operation was interrupted by a signal before any data was sent.
1978 @xref{Interrupted Primitives}.
1981 The descriptor @var{socket} is not a socket.
1984 The socket type requires that the message be sent atomically, but the
1985 message is too large for this to be possible.
1988 Nonblocking mode has been set on the socket, and the write operation
1989 would block. (Normally @code{send} blocks until the operation can be
1993 There is not enough internal buffer space available.
1996 You never connected this socket.
1999 This socket was connected but the connection is now broken. In this
2000 case, @code{send} generates a @code{SIGPIPE} signal first; if that
2001 signal is ignored or blocked, or if its handler returns, then
2002 @code{send} fails with @code{EPIPE}.
2006 @node Receiving Data
2007 @subsubsection Receiving Data
2009 @pindex sys/socket.h
2010 The @code{recv} function is declared in the header file
2011 @file{sys/socket.h}. If your @var{flags} argument is zero, you can
2012 just as well use @code{read} instead of @code{recv}; see @ref{I/O
2015 @comment sys/socket.h
2017 @deftypefun int recv (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags})
2018 The @code{recv} function is like @code{read}, but with the additional
2019 flags @var{flags}. The possible values of @var{flags} are described
2020 In @ref{Socket Data Options}.
2022 If nonblocking mode is set for @var{socket}, and no data is available to
2023 be read, @code{recv} fails immediately rather than waiting. @xref{File
2024 Status Flags}, for information about nonblocking mode.
2026 This function returns the number of bytes received, or @code{-1} on failure.
2027 The following @code{errno} error conditions are defined for this function:
2031 The @var{socket} argument is not a valid file descriptor.
2034 The descriptor @var{socket} is not a socket.
2037 Nonblocking mode has been set on the socket, and the read operation
2038 would block. (Normally, @code{recv} blocks until there is input
2039 available to be read.)
2042 The operation was interrupted by a signal before any data was read.
2043 @xref{Interrupted Primitives}.
2046 You never connected this socket.
2050 @node Socket Data Options
2051 @subsubsection Socket Data Options
2053 @pindex sys/socket.h
2054 The @var{flags} argument to @code{send} and @code{recv} is a bit
2055 mask. You can bitwise-OR the values of the following macros together
2056 to obtain a value for this argument. All are defined in the header
2057 file @file{sys/socket.h}.
2059 @comment sys/socket.h
2061 @deftypevr Macro int MSG_OOB
2062 Send or receive out-of-band data. @xref{Out-of-Band Data}.
2065 @comment sys/socket.h
2067 @deftypevr Macro int MSG_PEEK
2068 Look at the data but don't remove it from the input queue. This is
2069 only meaningful with input functions such as @code{recv}, not with
2073 @comment sys/socket.h
2075 @deftypevr Macro int MSG_DONTROUTE
2076 Don't include routing information in the message. This is only
2077 meaningful with output operations, and is usually only of interest for
2078 diagnostic or routing programs. We don't try to explain it here.
2081 @node Byte Stream Example
2082 @subsection Byte Stream Socket Example
2084 Here is an example client program that makes a connection for a byte
2085 stream socket in the Internet namespace. It doesn't do anything
2086 particularly interesting once it has connected to the server; it just
2087 sends a text string to the server and exits.
2090 @include inetcli.c.texi
2093 @node Server Example
2094 @subsection Byte Stream Connection Server Example
2096 The server end is much more complicated. Since we want to allow
2097 multiple clients to be connected to the server at the same time, it
2098 would be incorrect to wait for input from a single client by simply
2099 calling @code{read} or @code{recv}. Instead, the right thing to do is
2100 to use @code{select} (@pxref{Waiting for I/O}) to wait for input on
2101 all of the open sockets. This also allows the server to deal with
2102 additional connection requests.
2104 This particular server doesn't do anything interesting once it has
2105 gotten a message from a client. It does close the socket for that
2106 client when it detects an end-of-file condition (resulting from the
2107 client shutting down its end of the connection).
2109 This program uses @code{make_socket} and @code{init_sockaddr} to set
2110 up the socket address; see @ref{Inet Example}.
2113 @include inetsrv.c.texi
2116 @node Out-of-Band Data
2117 @subsection Out-of-Band Data
2119 @cindex out-of-band data
2120 @cindex high-priority data
2121 Streams with connections permit @dfn{out-of-band} data that is
2122 delivered with higher priority than ordinary data. Typically the
2123 reason for sending out-of-band data is to send notice of an
2124 exceptional condition. The way to send out-of-band data is using
2125 @code{send}, specifying the flag @code{MSG_OOB} (@pxref{Sending
2128 Out-of-band data is received with higher priority because the
2129 receiving process need not read it in sequence; to read the next
2130 available out-of-band data, use @code{recv} with the @code{MSG_OOB}
2131 flag (@pxref{Receiving Data}). Ordinary read operations do not read
2132 out-of-band data; they read only the ordinary data.
2134 @cindex urgent socket condition
2135 When a socket finds that out-of-band data is on its way, it sends a
2136 @code{SIGURG} signal to the owner process or process group of the
2137 socket. You can specify the owner using the @code{F_SETOWN} command
2138 to the @code{fcntl} function; see @ref{Interrupt Input}. You must
2139 also establish a handler for this signal, as described in @ref{Signal
2140 Handling}, in order to take appropriate action such as reading the
2143 Alternatively, you can test for pending out-of-band data, or wait
2144 until there is out-of-band data, using the @code{select} function; it
2145 can wait for an exceptional condition on the socket. @xref{Waiting
2146 for I/O}, for more information about @code{select}.
2148 Notification of out-of-band data (whether with @code{SIGURG} or with
2149 @code{select}) indicates that out-of-band data is on the way; the data
2150 may not actually arrive until later. If you try to read the
2151 out-of-band data before it arrives, @code{recv} fails with an
2152 @code{EWOULDBLOCK} error.
2154 Sending out-of-band data automatically places a ``mark'' in the stream
2155 of ordinary data, showing where in the sequence the out-of-band data
2156 ``would have been''. This is useful when the meaning of out-of-band
2157 data is ``cancel everything sent so far''. Here is how you can test,
2158 in the receiving process, whether any ordinary data was sent before
2162 success = ioctl (socket, SIOCATMARK, &result);
2165 Here's a function to discard any ordinary data preceding the
2170 discard_until_mark (int socket)
2174 /* @r{This is not an arbitrary limit; any size will do.} */
2176 int result, success;
2178 /* @r{If we have reached the mark, return.} */
2179 success = ioctl (socket, SIOCATMARK, &result);
2185 /* @r{Otherwise, read a bunch of ordinary data and discard it.}
2186 @r{This is guaranteed not to read past the mark}
2187 @r{if it starts before the mark.} */
2188 success = read (socket, buffer, sizeof buffer);
2195 If you don't want to discard the ordinary data preceding the mark, you
2196 may need to read some of it anyway, to make room in internal system
2197 buffers for the out-of-band data. If you try to read out-of-band data
2198 and get an @code{EWOULDBLOCK} error, try reading some ordinary data
2199 (saving it so that you can use it when you want it) and see if that
2200 makes room. Here is an example:
2207 struct buffer *next;
2210 /* @r{Read the out-of-band data from SOCKET and return it}
2211 @r{as a `struct buffer', which records the address of the data}
2214 @r{It may be necessary to read some ordinary data}
2215 @r{in order to make room for the out-of-band data.}
2216 @r{If so, the ordinary data is saved as a chain of buffers}
2217 @r{found in the `next' field of the value.} */
2220 read_oob (int socket)
2222 struct buffer *tail = 0;
2223 struct buffer *list = 0;
2227 /* @r{This is an arbitrary limit.}
2228 @r{Does anyone know how to do this without a limit?} */
2229 char *buffer = (char *) xmalloc (1024);
2230 struct buffer *link;
2234 /* @r{Try again to read the out-of-band data.} */
2235 success = recv (socket, buffer, sizeof buffer, MSG_OOB);
2238 /* @r{We got it, so return it.} */
2240 = (struct buffer *) xmalloc (sizeof (struct buffer));
2241 link->buffer = buffer;
2242 link->size = success;
2247 /* @r{If we fail, see if we are at the mark.} */
2248 success = ioctl (socket, SIOCATMARK, &result);
2253 /* @r{At the mark; skipping past more ordinary data cannot help.}
2254 @r{So just wait a while.} */
2259 /* @r{Otherwise, read a bunch of ordinary data and save it.}
2260 @r{This is guaranteed not to read past the mark}
2261 @r{if it starts before the mark.} */
2262 success = read (socket, buffer, sizeof buffer);
2266 /* @r{Save this data in the buffer list.} */
2269 = (struct buffer *) xmalloc (sizeof (struct buffer));
2270 link->buffer = buffer;
2271 link->size = success;
2273 /* @r{Add the new link to the end of the list.} */
2285 @section Datagram Socket Operations
2287 @cindex datagram socket
2288 This section describes how to use communication styles that don't use
2289 connections (styles @code{SOCK_DGRAM} and @code{SOCK_RDM}). Using
2290 these styles, you group data into packets and each packet is an
2291 independent communication. You specify the destination for each
2292 packet individually.
2294 Datagram packets are like letters: you send each one independently,
2295 with its own destination address, and they may arrive in the wrong
2296 order or not at all.
2298 The @code{listen} and @code{accept} functions are not allowed for
2299 sockets using connectionless communication styles.
2302 * Sending Datagrams:: Sending packets on a datagram socket.
2303 * Receiving Datagrams:: Receiving packets on a datagram socket.
2304 * Datagram Example:: An example program: packets sent over a
2305 datagram socket in the file namespace.
2306 * Example Receiver:: Another program, that receives those packets.
2309 @node Sending Datagrams
2310 @subsection Sending Datagrams
2311 @cindex sending a datagram
2312 @cindex transmitting datagrams
2313 @cindex datagrams, transmitting
2315 @pindex sys/socket.h
2316 The normal way of sending data on a datagram socket is by using the
2317 @code{sendto} function, declared in @file{sys/socket.h}.
2319 You can call @code{connect} on a datagram socket, but this only
2320 specifies a default destination for further data transmission on the
2321 socket. When a socket has a default destination, then you can use
2322 @code{send} (@pxref{Sending Data}) or even @code{write} (@pxref{I/O
2323 Primitives}) to send a packet there. You can cancel the default
2324 destination by calling @code{connect} using an address format of
2325 @code{AF_UNSPEC} in the @var{addr} argument. @xref{Connecting}, for
2326 more information about the @code{connect} function.
2328 @comment sys/socket.h
2330 @deftypefun int sendto (int @var{socket}, void *@var{buffer}. size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, size_t @var{length})
2331 The @code{sendto} function transmits the data in the @var{buffer}
2332 through the socket @var{socket} to the destination address specified
2333 by the @var{addr} and @var{length} arguments. The @var{size} argument
2334 specifies the number of bytes to be transmitted.
2336 The @var{flags} are interpreted the same way as for @code{send}; see
2337 @ref{Socket Data Options}.
2339 The return value and error conditions are also the same as for
2340 @code{send}, but you cannot rely on the system to detect errors and
2341 report them; the most common error is that the packet is lost or there
2342 is no one at the specified address to receive it, and the operating
2343 system on your machine usually does not know this.
2345 It is also possible for one call to @code{sendto} to report an error
2346 due to a problem related to a previous call.
2349 @node Receiving Datagrams
2350 @subsection Receiving Datagrams
2351 @cindex receiving datagrams
2353 The @code{recvfrom} function reads a packet from a datagram socket and
2354 also tells you where it was sent from. This function is declared in
2355 @file{sys/socket.h}.
2357 @comment sys/socket.h
2359 @deftypefun int recvfrom (int @var{socket}, void *@var{buffer}, size_t @var{size}, int @var{flags}, struct sockaddr *@var{addr}, size_t *@var{length-ptr})
2360 The @code{recvfrom} function reads one packet from the socket
2361 @var{socket} into the buffer @var{buffer}. The @var{size} argument
2362 specifies the maximum number of bytes to be read.
2364 If the packet is longer than @var{size} bytes, then you get the first
2365 @var{size} bytes of the packet, and the rest of the packet is lost.
2366 There's no way to read the rest of the packet. Thus, when you use a
2367 packet protocol, you must always know how long a packet to expect.
2369 The @var{addr} and @var{length-ptr} arguments are used to return the
2370 address where the packet came from. @xref{Socket Addresses}. For a
2371 socket in the file domain, the address information won't be meaningful,
2372 since you can't read the address of such a socket (@pxref{File
2373 Namespace}). You can specify a null pointer as the @var{addr} argument
2374 if you are not interested in this information.
2376 The @var{flags} are interpreted the same way as for @code{recv}
2377 (@pxref{Socket Data Options}). The return value and error conditions
2378 are also the same as for @code{recv}.
2381 You can use plain @code{recv} (@pxref{Receiving Data}) instead of
2382 @code{recvfrom} if you know don't need to find out who sent the packet
2383 (either because you know where it should come from or because you
2384 treat all possible senders alike). Even @code{read} can be used if
2385 you don't want to specify @var{flags} (@pxref{I/O Primitives}).
2388 @c sendmsg and recvmsg are like readv and writev in that they
2389 @c use a series of buffers. It's not clear this is worth
2390 @c supporting or that we support them.
2391 @c !!! they can do more; it is hairy
2393 @comment sys/socket.h
2395 @deftp {Data Type} {struct msghdr}
2398 @comment sys/socket.h
2400 @deftypefun int sendmsg (int @var{socket}, const struct msghdr *@var{message}, int @var{flags})
2403 @comment sys/socket.h
2405 @deftypefun int recvmsg (int @var{socket}, struct msghdr *@var{message}, int @var{flags})
2409 @node Datagram Example
2410 @subsection Datagram Socket Example
2412 Here is a set of example programs that send messages over a datagram
2413 stream in the file namespace. Both the client and server programs use the
2414 @code{make_named_socket} function that was presented in @ref{File
2415 Namespace}, to create and name their sockets.
2417 First, here is the server program. It sits in a loop waiting for
2418 messages to arrive, bouncing each message back to the sender.
2419 Obviously, this isn't a particularly useful program, but it does show
2420 the general ideas involved.
2423 @include filesrv.c.texi
2426 @node Example Receiver
2427 @subsection Example of Reading Datagrams
2429 Here is the client program corresponding to the server above.
2431 It sends a datagram to the server and then waits for a reply. Notice
2432 that the socket for the client (as well as for the server) in this
2433 example has to be given a name. This is so that the server can direct
2434 a message back to the client. Since the socket has no associated
2435 connection state, the only way the server can do this is by
2436 referencing the name of the client.
2439 @include filecli.c.texi
2442 Keep in mind that datagram socket communications are unreliable. In
2443 this example, the client program waits indefinitely if the message
2444 never reaches the server or if the server's response never comes
2445 back. It's up to the user running the program to kill it and restart
2446 it, if desired. A more automatic solution could be to use
2447 @code{select} (@pxref{Waiting for I/O}) to establish a timeout period
2448 for the reply, and in case of timeout either resend the message or
2449 shut down the socket and exit.
2452 @section The @code{inetd} Daemon
2454 We've explained above how to write a server program that does its own
2455 listening. Such a server must already be running in order for anyone
2458 Another way to provide service for an Internet port is to let the daemon
2459 program @code{inetd} do the listening. @code{inetd} is a program that
2460 runs all the time and waits (using @code{select}) for messages on a
2461 specified set of ports. When it receives a message, it accepts the
2462 connection (if the socket style calls for connections) and then forks a
2463 child process to run the corresponding server program. You specify the
2464 ports and their programs in the file @file{/etc/inetd.conf}.
2468 * Configuring Inetd::
2472 @subsection @code{inetd} Servers
2474 Writing a server program to be run by @code{inetd} is very simple. Each time
2475 someone requests a connection to the appropriate port, a new server
2476 process starts. The connection already exists at this time; the
2477 socket is available as the standard input descriptor and as the
2478 standard output descriptor (descriptors 0 and 1) in the server
2479 process. So the server program can begin reading and writing data
2480 right away. Often the program needs only the ordinary I/O facilities;
2481 in fact, a general-purpose filter program that knows nothing about
2482 sockets can work as a byte stream server run by @code{inetd}.
2484 You can also use @code{inetd} for servers that use connectionless
2485 communication styles. For these servers, @code{inetd} does not try to accept
2486 a connection, since no connection is possible. It just starts the
2487 server program, which can read the incoming datagram packet from
2488 descriptor 0. The server program can handle one request and then
2489 exit, or you can choose to write it to keep reading more requests
2490 until no more arrive, and then exit. You must specify which of these
2491 two techniques the server uses, when you configure @code{inetd}.
2493 @node Configuring Inetd
2494 @subsection Configuring @code{inetd}
2496 The file @file{/etc/inetd.conf} tells @code{inetd} which ports to listen to
2497 and what server programs to run for them. Normally each entry in the
2498 file is one line, but you can split it onto multiple lines provided
2499 all but the first line of the entry start with whitespace. Lines that
2500 start with @samp{#} are comments.
2502 Here are two standard entries in @file{/etc/inetd.conf}:
2505 ftp stream tcp nowait root /libexec/ftpd ftpd
2506 talk dgram udp wait root /libexec/talkd talkd
2509 An entry has this format:
2512 @var{service} @var{style} @var{protocol} @var{wait} @var{username} @var{program} @var{arguments}
2515 The @var{service} field says which service this program provides. It
2516 should be the name of a service defined in @file{/etc/services}.
2517 @code{inetd} uses @var{service} to decide which port to listen on for
2520 The fields @var{style} and @var{protocol} specify the communication
2521 style and the protocol to use for the listening socket. The style
2522 should be the name of a communication style, converted to lower case
2523 and with @samp{SOCK_} deleted---for example, @samp{stream} or
2524 @samp{dgram}. @var{protocol} should be one of the protocols listed in
2525 @file{/etc/protocols}. The typical protocol names are @samp{tcp} for
2526 byte stream connections and @samp{udp} for unreliable datagrams.
2528 The @var{wait} field should be either @samp{wait} or @samp{nowait}.
2529 Use @samp{wait} if @var{style} is a connectionless style and the
2530 server, once started, handles multiple requests, as many as come in.
2531 Use @samp{nowait} if @code{inetd} should start a new process for each message
2532 or request that comes in. If @var{style} uses connections, then
2533 @var{wait} @strong{must} be @samp{nowait}.
2535 @var{user} is the user name that the server should run as. @code{inetd} runs
2536 as root, so it can set the user ID of its children arbitrarily. It's
2537 best to avoid using @samp{root} for @var{user} if you can; but some
2538 servers, such as Telnet and FTP, read a username and password
2539 themselves. These servers need to be root initially so they can log
2540 in as commanded by the data coming over the network.
2542 @var{program} together with @var{arguments} specifies the command to
2543 run to start the server. @var{program} should be an absolute file
2544 name specifying the executable file to run. @var{arguments} consists
2545 of any number of whitespace-separated words, which become the
2546 command-line arguments of @var{program}. The first word in
2547 @var{arguments} is argument zero, which should by convention be the
2548 program name itself (sans directories).
2550 If you edit @file{/etc/inetd.conf}, you can tell @code{inetd} to reread the
2551 file and obey its new contents by sending the @code{inetd} process the
2552 @code{SIGHUP} signal. You'll have to use @code{ps} to determine the
2553 process ID of the @code{inetd} process, as it is not fixed.
2555 @c !!! could document /etc/inetd.sec
2557 @node Socket Options
2558 @section Socket Options
2559 @cindex socket options
2561 This section describes how to read or set various options that modify
2562 the behavior of sockets and their underlying communications protocols.
2564 @cindex level, for socket options
2565 @cindex socket option level
2566 When you are manipulating a socket option, you must specify which
2567 @dfn{level} the option pertains to. This describes whether the option
2568 applies to the socket interface, or to a lower-level communications
2572 * Socket Option Functions:: The basic functions for setting and getting
2574 * Socket-Level Options:: Details of the options at the socket level.
2577 @node Socket Option Functions
2578 @subsection Socket Option Functions
2580 @pindex sys/socket.h
2581 Here are the functions for examining and modifying socket options.
2582 They are declared in @file{sys/socket.h}.
2584 @comment sys/socket.h
2586 @deftypefun int getsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, size_t *@var{optlen-ptr})
2587 The @code{getsockopt} function gets information about the value of
2588 option @var{optname} at level @var{level} for socket @var{socket}.
2590 The option value is stored in a buffer that @var{optval} points to.
2591 Before the call, you should supply in @code{*@var{optlen-ptr}} the
2592 size of this buffer; on return, it contains the number of bytes of
2593 information actually stored in the buffer.
2595 Most options interpret the @var{optval} buffer as a single @code{int}
2598 The actual return value of @code{getsockopt} is @code{0} on success
2599 and @code{-1} on failure. The following @code{errno} error conditions
2604 The @var{socket} argument is not a valid file descriptor.
2607 The descriptor @var{socket} is not a socket.
2610 The @var{optname} doesn't make sense for the given @var{level}.
2614 @comment sys/socket.h
2616 @deftypefun int setsockopt (int @var{socket}, int @var{level}, int @var{optname}, void *@var{optval}, size_t @var{optlen})
2617 This function is used to set the socket option @var{optname} at level
2618 @var{level} for socket @var{socket}. The value of the option is passed
2619 in the buffer @var{optval}, which has size @var{optlen}.
2621 The return value and error codes for @code{setsockopt} are the same as
2622 for @code{getsockopt}.
2625 @node Socket-Level Options
2626 @subsection Socket-Level Options
2628 @comment sys/socket.h
2630 @deftypevr Constant int SOL_SOCKET
2631 Use this constant as the @var{level} argument to @code{getsockopt} or
2632 @code{setsockopt} to manipulate the socket-level options described in
2636 @pindex sys/socket.h
2637 Here is a table of socket-level option names; all are defined in the
2638 header file @file{sys/socket.h}.
2641 @comment sys/socket.h
2644 @c Extra blank line here makes the table look better.
2646 This option toggles recording of debugging information in the underlying
2647 protocol modules. The value has type @code{int}; a nonzero value means
2649 @c !!! should say how this is used
2650 @c Ok, anyone who knows, please explain.
2652 @comment sys/socket.h
2655 This option controls whether @code{bind} (@pxref{Setting Address})
2656 should permit reuse of local addresses for this socket. If you enable
2657 this option, you can actually have two sockets with the same Internet
2658 port number; but the system won't allow you to use the two
2659 identically-named sockets in a way that would confuse the Internet. The
2660 reason for this option is that some higher-level Internet protocols,
2661 including FTP, require you to keep reusing the same socket number.
2663 The value has type @code{int}; a nonzero value means ``yes''.
2665 @comment sys/socket.h
2668 This option controls whether the underlying protocol should
2669 periodically transmit messages on a connected socket. If the peer
2670 fails to respond to these messages, the connection is considered
2671 broken. The value has type @code{int}; a nonzero value means
2674 @comment sys/socket.h
2677 This option controls whether outgoing messages bypass the normal
2678 message routing facilities. If set, messages are sent directly to the
2679 network interface instead. The value has type @code{int}; a nonzero
2680 value means ``yes''.
2682 @comment sys/socket.h
2685 This option specifies what should happen when the socket of a type
2686 that promises reliable delivery still has untransmitted messages when
2687 it is closed; see @ref{Closing a Socket}. The value has type
2688 @code{struct linger}.
2690 @comment sys/socket.h
2692 @deftp {Data Type} {struct linger}
2693 This structure type has the following members:
2697 This field is interpreted as a boolean. If nonzero, @code{close}
2698 blocks until the data is transmitted or the timeout period has expired.
2701 This specifies the timeout period, in seconds.
2705 @comment sys/socket.h
2708 This option controls whether datagrams may be broadcast from the socket.
2709 The value has type @code{int}; a nonzero value means ``yes''.
2711 @comment sys/socket.h
2714 If this option is set, out-of-band data received on the socket is
2715 placed in the normal input queue. This permits it to be read using
2716 @code{read} or @code{recv} without specifying the @code{MSG_OOB}
2717 flag. @xref{Out-of-Band Data}. The value has type @code{int}; a
2718 nonzero value means ``yes''.
2720 @comment sys/socket.h
2723 This option gets or sets the size of the output buffer. The value is a
2724 @code{size_t}, which is the size in bytes.
2726 @comment sys/socket.h
2729 This option gets or sets the size of the input buffer. The value is a
2730 @code{size_t}, which is the size in bytes.
2732 @comment sys/socket.h
2735 @comment sys/socket.h
2738 This option can be used with @code{getsockopt} only. It is used to
2739 get the socket's communication style. @code{SO_TYPE} is the
2740 historical name, and @code{SO_STYLE} is the preferred name in GNU.
2741 The value has type @code{int} and its value designates a communication
2742 style; see @ref{Communication Styles}.
2744 @comment sys/socket.h
2747 @c Extra blank line here makes the table look better.
2749 This option can be used with @code{getsockopt} only. It is used to reset
2750 the error status of the socket. The value is an @code{int}, which represents
2751 the previous error status.
2752 @c !!! what is "socket error status"? this is never defined.
2755 @node Networks Database
2756 @section Networks Database
2757 @cindex networks database
2758 @cindex converting network number to network name
2759 @cindex converting network name to network number
2761 @pindex /etc/networks
2763 Many systems come with a database that records a list of networks known
2764 to the system developer. This is usually kept either in the file
2765 @file{/etc/networks} or in an equivalent from a name server. This data
2766 base is useful for routing programs such as @code{route}, but it is not
2767 useful for programs that simply communicate over the network. We
2768 provide functions to access this data base, which are declared in
2773 @deftp {Data Type} {struct netent}
2774 This data type is used to represent information about entries in the
2775 networks database. It has the following members:
2779 This is the ``official'' name of the network.
2781 @item char **n_aliases
2782 These are alternative names for the network, represented as a vector
2783 of strings. A null pointer terminates the array.
2785 @item int n_addrtype
2786 This is the type of the network number; this is always equal to
2787 @code{AF_INET} for Internet networks.
2789 @item unsigned long int n_net
2790 This is the network number. Network numbers are returned in host
2791 byte order; see @ref{Byte Order}.
2795 Use the @code{getnetbyname} or @code{getnetbyaddr} functions to search
2796 the networks database for information about a specific network. The
2797 information is returned in a statically-allocated structure; you must
2798 copy the information if you need to save it.
2802 @deftypefun {struct netent *} getnetbyname (const char *@var{name})
2803 The @code{getnetbyname} function returns information about the network
2804 named @var{name}. It returns a null pointer if there is no such
2810 @deftypefun {struct netent *} getnetbyaddr (long @var{net}, int @var{type})
2811 The @code{getnetbyaddr} function returns information about the network
2812 of type @var{type} with number @var{net}. You should specify a value of
2813 @code{AF_INET} for the @var{type} argument for Internet networks.
2815 @code{getnetbyaddr} returns a null pointer if there is no such
2819 You can also scan the networks database using @code{setnetent},
2820 @code{getnetent}, and @code{endnetent}. Be careful in using these
2821 functions, because they are not reentrant.
2825 @deftypefun void setnetent (int @var{stayopen})
2826 This function opens and rewinds the networks database.
2828 If the @var{stayopen} argument is nonzero, this sets a flag so that
2829 subsequent calls to @code{getnetbyname} or @code{getnetbyaddr} will
2830 not close the database (as they usually would). This makes for more
2831 efficiency if you call those functions several times, by avoiding
2832 reopening the database for each call.
2837 @deftypefun {struct netent *} getnetent (void)
2838 This function returns the next entry in the networks database. It
2839 returns a null pointer if there are no more entries.
2844 @deftypefun void endnetent (void)
2845 This function closes the networks database.