PageRenderTime 40ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Sources/selp_glibc-2.5.90-19.0.46/manual/socket.texi

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