1inet(3) Erlang Module Definition inet(3)
2
3
4
6 inet - Access to TCP/IP protocols.
7
9 This module provides access to TCP/IP protocols.
10
11 See also ERTS User's Guide: Inet Configuration for more information
12 about how to configure an Erlang runtime system for IP communication.
13
14 The following two Kernel configuration parameters affect the behavior
15 of all sockets opened on an Erlang node:
16
17 * inet_default_connect_options can contain a list of default options
18 used for all sockets returned when doing connect.
19
20 * inet_default_listen_options can contain a list of default options
21 used when issuing a listen call.
22
23 When accept is issued, the values of the listening socket options are
24 inherited. No such application variable is therefore needed for accept.
25
26 Using the Kernel configuration parameters above, one can set default
27 options for all TCP sockets on a node, but use this with care. Options
28 such as {delay_send,true} can be specified in this way. The following
29 is an example of starting an Erlang node with all sockets using delayed
30 send:
31
32 $ erl -sname test -kernel \
33 inet_default_connect_options '[{delay_send,true}]' \
34 inet_default_listen_options '[{delay_send,true}]'
35
36 Notice that default option {active, true} cannot be changed, for inter‐
37 nal reasons.
38
39 Addresses as inputs to functions can be either a string or a tuple. For
40 example, the IP address 150.236.20.73 can be passed to gethostbyaddr/1,
41 either as string "150.236.20.73" or as tuple {150, 236, 20, 73}.
42
43 IPv4 address examples:
44
45 Address ip_address()
46 ------- ------------
47 127.0.0.1 {127,0,0,1}
48 192.168.42.2 {192,168,42,2}
49
50 IPv6 address examples:
51
52 Address ip_address()
53 ------- ------------
54 ::1 {0,0,0,0,0,0,0,1}
55 ::192.168.42.2 {0,0,0,0,0,0,(192 bsl 8) bor 168,(42 bsl 8) bor 2}
56 ::FFFF:192.168.42.2
57 {0,0,0,0,0,16#FFFF,(192 bsl 8) bor 168,(42 bsl 8) bor 2}
58 3ffe:b80:1f8d:2:204:acff:fe17:bf38
59 {16#3ffe,16#b80,16#1f8d,16#2,16#204,16#acff,16#fe17,16#bf38}
60 fe80::204:acff:fe17:bf38
61 {16#fe80,0,0,0,0,16#204,16#acff,16#fe17,16#bf38}
62
63 Function parse_address/1 can be useful:
64
65 1> inet:parse_address("192.168.42.2").
66 {ok,{192,168,42,2}}
67 2> inet:parse_address("::FFFF:192.168.42.2").
68 {ok,{0,0,0,0,0,65535,49320,10754}}
69
71 hostent() =
72 #hostent{h_name = inet:hostname(),
73 h_aliases = [inet:hostname()],
74 h_addrtype = inet | inet6,
75 h_length = integer() >= 0,
76 h_addr_list = [inet:ip_address()]}
77
78 The record is defined in the Kernel include file "inet.hrl".
79
80 Add the following directive to the module:
81
82 -include_lib("kernel/include/inet.hrl").
83
84 hostname() = atom() | string()
85
86 ip_address() = ip4_address() | ip6_address()
87
88 ip4_address() = {0..255, 0..255, 0..255, 0..255}
89
90 ip6_address() =
91 {0..65535,
92 0..65535,
93 0..65535,
94 0..65535,
95 0..65535,
96 0..65535,
97 0..65535,
98 0..65535}
99
100 port_number() = 0..65535
101
102 local_address() = {local, File :: binary() | string()}
103
104 This address family only works on Unix-like systems.
105
106 File is normally a file pathname in a local filesystem. It is
107 limited in length by the operating system, traditionally to 108
108 bytes.
109
110 A binary() is passed as is to the operating system, but a
111 string() is encoded according to the system filename encoding
112 mode.
113
114 Other addresses are possible, for example Linux implements
115 "Abstract Addresses". See the documentation for Unix Domain
116 Sockets on your system, normally unix in manual section 7.
117
118 In most API functions where you can use this address family the
119 port number must be 0.
120
121 socket_address() =
122 ip_address() | any | loopback | local_address()
123
124 socket_getopt() =
125 gen_sctp:option_name() |
126 gen_tcp:option_name() |
127 gen_udp:option_name()
128
129 socket_setopt() =
130 gen_sctp:option() | gen_tcp:option() | gen_udp:option()
131
132 returned_non_ip_address() =
133 {local, binary()} | {unspec, <<>>} | {undefined, any()}
134
135 Addresses besides ip_address() ones that are returned from
136 socket API functions. See in particular local_address(). The
137 unspec family corresponds to AF_UNSPEC and can occur if the
138 other side has no socket address. The undefined family can only
139 occur in the unlikely event of an address family that the VM
140 does not recognize.
141
142 posix() = exbadport | exbadseq | file:posix()
143
144 An atom that is named from the POSIX error codes used in Unix,
145 and in the runtime libraries of most C compilers. See section
146 POSIX Error Codes.
147
148 socket()
149
150 See gen_tcp:type-socket and gen_udp:type-socket.
151
152 address_family() = inet | inet6 | local
153
155 close(Socket) -> ok
156
157 Types:
158
159 Socket = socket()
160
161 Closes a socket of any type.
162
163 format_error(Reason) -> string()
164
165 Types:
166
167 Reason = posix() | system_limit
168
169 Returns a diagnostic error string. For possible POSIX values and
170 corresponding strings, see section POSIX Error Codes.
171
172 get_rc() ->
173 [{Par :: atom(), Val :: any()} |
174 {Par :: atom(), Val1 :: any(), Val2 :: any()}]
175
176 Returns the state of the Inet configuration database in form of
177 a list of recorded configuration parameters. For more informa‐
178 tion, see ERTS User's Guide: Inet Configuration.
179
180 Only actual parameters with other than default values are
181 returned, for example not directives that specify other sources
182 for configuration parameters nor directives that clear parame‐
183 ters.
184
185 getaddr(Host, Family) -> {ok, Address} | {error, posix()}
186
187 Types:
188
189 Host = ip_address() | hostname()
190 Family = address_family()
191 Address = ip_address()
192
193 Returns the IP address for Host as a tuple of integers. Host can
194 be an IP address, a single hostname, or a fully qualified host‐
195 name.
196
197 getaddrs(Host, Family) -> {ok, Addresses} | {error, posix()}
198
199 Types:
200
201 Host = ip_address() | hostname()
202 Family = address_family()
203 Addresses = [ip_address()]
204
205 Returns a list of all IP addresses for Host. Host can be an IP
206 address, a single hostname, or a fully qualified hostname.
207
208 gethostbyaddr(Address) -> {ok, Hostent} | {error, posix()}
209
210 Types:
211
212 Address = string() | ip_address()
213 Hostent = hostent()
214
215 Returns a hostent record for the host with the specified
216 address.
217
218 gethostbyname(Hostname) -> {ok, Hostent} | {error, posix()}
219
220 Types:
221
222 Hostname = hostname()
223 Hostent = hostent()
224
225 Returns a hostent record for the host with the specified host‐
226 name.
227
228 If resolver option inet6 is true, an IPv6 address is looked up.
229 If that fails, the IPv4 address is looked up and returned on
230 IPv6-mapped IPv4 format.
231
232 gethostbyname(Hostname, Family) ->
233 {ok, Hostent} | {error, posix()}
234
235 Types:
236
237 Hostname = hostname()
238 Family = address_family()
239 Hostent = hostent()
240
241 Returns a hostent record for the host with the specified name,
242 restricted to the specified address family.
243
244 gethostname() -> {ok, Hostname}
245
246 Types:
247
248 Hostname = string()
249
250 Returns the local hostname. Never fails.
251
252 getifaddrs() -> {ok, Iflist} | {error, posix()}
253
254 Types:
255
256 Iflist = [{Ifname, [Ifopt]}]
257 Ifname = string()
258 Ifopt =
259 {flags, [Flag]} |
260 {addr, Addr} |
261 {netmask, Netmask} |
262 {broadaddr, Broadaddr} |
263 {dstaddr, Dstaddr} |
264 {hwaddr, Hwaddr}
265 Flag =
266 up | broadcast | loopback | pointtopoint | running | mul‐
267 ticast
268 Addr = Netmask = Broadaddr = Dstaddr = ip_address()
269 Hwaddr = [byte()]
270
271 Returns a list of 2-tuples containing interface names and the
272 interface addresses. Ifname is a Unicode string. Hwaddr is hard‐
273 ware dependent, for example, on Ethernet interfaces it is the
274 6-byte Ethernet address (MAC address (EUI-48 address)).
275
276 The tuples {addr,Addr}, {netmask,_}, and {broadaddr,_} are
277 repeated in the result list if the interface has multiple
278 addresses. If you come across an interface with multiple
279 {flag,_} or {hwaddr,_} tuples, you have a strange interface or
280 possibly a bug in this function. The tuple {flag,_} is manda‐
281 tory, all others are optional.
282
283 Do not rely too much on the order of Flag atoms or Ifopt tuples.
284 There are however some rules:
285
286 * Immediately after {addr,_} follows {netmask,_}.
287
288 * Immediately thereafter follows {broadaddr,_} if flag broad‐
289 cast is not set and flag pointtopoint is set.
290
291 * Any {netmask,_}, {broadaddr,_}, or {dstaddr,_} tuples that
292 follow an {addr,_} tuple concerns that address.
293
294 The tuple {hwaddr,_} is not returned on Solaris, as the hardware
295 address historically belongs to the link layer and only the
296 superuser can read such addresses.
297
298 Warning:
299 On Windows, the data is fetched from different OS API functions,
300 so the Netmask and Broadaddr values can be calculated, just as
301 some Flag values. Report flagrant bugs.
302
303
304 getopts(Socket, Options) -> {ok, OptionValues} | {error, posix()}
305
306 Types:
307
308 Socket = socket()
309 Options = [socket_getopt()]
310 OptionValues = [socket_setopt()]
311
312 Gets one or more options for a socket. For a list of available
313 options, see setopts/2.
314
315 The number of elements in the returned OptionValues list does
316 not necessarily correspond to the number of options asked for.
317 If the operating system fails to support an option, it is left
318 out in the returned list. An error tuple is returned only when
319 getting options for the socket is impossible (that is, the
320 socket is closed or the buffer size in a raw request is too
321 large). This behavior is kept for backward compatibility rea‐
322 sons.
323
324 A raw option request RawOptReq = {raw, Protocol, OptionNum, Val‐
325 ueSpec} can be used to get information about socket options not
326 (explicitly) supported by the emulator. The use of raw socket
327 options makes the code non-portable, but allows the Erlang pro‐
328 grammer to take advantage of unusual features present on the
329 current platform.
330
331 RawOptReq consists of tag raw followed by the protocol level,
332 the option number, and either a binary or the size, in bytes, of
333 the buffer in which the option value is to be stored. A binary
334 is to be used when the underlying getsockopt requires input in
335 the argument field. In this case, the binary size is to corre‐
336 spond to the required buffer size of the return value. The sup‐
337 plied values in a RawOptReq correspond to the second, third, and
338 fourth/fifth parameters to the getsockopt call in the C socket
339 API. The value stored in the buffer is returned as a binary Val‐
340 ueBin, where all values are coded in the native endianess.
341
342 Asking for and inspecting raw socket options require low-level
343 information about the current operating system and TCP stack.
344
345 Example:
346
347 Consider a Linux machine where option TCP_INFO can be used to
348 collect TCP statistics for a socket. Assume you are interested
349 in field tcpi_sacked of struct tcp_info filled in when asking
350 for TCP_INFO. To be able to access this information, you need to
351 know the following:
352
353 * The numeric value of protocol level IPPROTO_TCP
354
355 * The numeric value of option TCP_INFO
356
357 * The size of struct tcp_info
358
359 * The size and offset of the specific field
360
361 By inspecting the headers or writing a small C program, it is
362 found that IPPROTO_TCP is 6, TCP_INFO is 11, the structure size
363 is 92 (bytes), the offset of tcpi_sacked is 28 bytes, and the
364 value is a 32-bit integer. The following code can be used to
365 retrieve the value:
366
367 get_tcpi_sacked(Sock) ->
368 {ok,[{raw,_,_,Info}]} = inet:getopts(Sock,[{raw,6,11,92}]),
369 <<_:28/binary,TcpiSacked:32/native,_/binary>> = Info,
370 TcpiSacked.
371
372 Preferably, you would check the machine type, the operating sys‐
373 tem, and the Kernel version before executing anything similar to
374 this code.
375
376 getstat(Socket) -> {ok, OptionValues} | {error, posix()}
377
378 getstat(Socket, Options) -> {ok, OptionValues} | {error, posix()}
379
380 Types:
381
382 Socket = socket()
383 Options = [stat_option()]
384 OptionValues = [{stat_option(), integer()}]
385 stat_option() =
386 recv_cnt |
387 recv_max |
388 recv_avg |
389 recv_oct |
390 recv_dvi |
391 send_cnt |
392 send_max |
393 send_avg |
394 send_oct |
395 send_pend
396
397 Gets one or more statistic options for a socket.
398
399 getstat(Socket) is equivalent to getstat(Socket, [recv_avg,
400 recv_cnt, recv_dvi, recv_max, recv_oct, send_avg, send_cnt,
401 send_dvi, send_max, send_oct]).
402
403 The following options are available:
404
405 recv_avg:
406 Average size of packets, in bytes, received by the socket.
407
408 recv_cnt:
409 Number of packets received by the socket.
410
411 recv_dvi:
412 Average packet size deviation, in bytes, received by the
413 socket.
414
415 recv_max:
416 Size of the largest packet, in bytes, received by the
417 socket.
418
419 recv_oct:
420 Number of bytes received by the socket.
421
422 send_avg:
423 Average size of packets, in bytes, sent from the socket.
424
425 send_cnt:
426 Number of packets sent from the socket.
427
428 send_dvi:
429 Average packet size deviation, in bytes, sent from the
430 socket.
431
432 send_max:
433 Size of the largest packet, in bytes, sent from the socket.
434
435 send_oct:
436 Number of bytes sent from the socket.
437
438 ntoa(IpAddress) -> Address | {error, einval}
439
440 Types:
441
442 Address = string()
443 IpAddress = ip_address()
444
445 Parses an ip_address() and returns an IPv4 or IPv6 address
446 string.
447
448 parse_address(Address) -> {ok, IPAddress} | {error, einval}
449
450 Types:
451
452 Address = string()
453 IPAddress = ip_address()
454
455 Parses an IPv4 or IPv6 address string and returns an
456 ip4_address() or ip6_address(). Accepts a shortened IPv4 address
457 string.
458
459 parse_ipv4_address(Address) -> {ok, IPv4Address} | {error, einval}
460
461 Types:
462
463 Address = string()
464 IPv4Address = ip_address()
465
466 Parses an IPv4 address string and returns an ip4_address().
467 Accepts a shortened IPv4 address string.
468
469 parse_ipv4strict_address(Address) ->
470 {ok, IPv4Address} | {error, einval}
471
472 Types:
473
474 Address = string()
475 IPv4Address = ip_address()
476
477 Parses an IPv4 address string containing four fields, that is,
478 not shortened, and returns an ip4_address().
479
480 parse_ipv6_address(Address) -> {ok, IPv6Address} | {error, einval}
481
482 Types:
483
484 Address = string()
485 IPv6Address = ip_address()
486
487 Parses an IPv6 address string and returns an ip6_address(). If
488 an IPv4 address string is specified, an IPv4-mapped IPv6 address
489 is returned.
490
491 parse_ipv6strict_address(Address) ->
492 {ok, IPv6Address} | {error, einval}
493
494 Types:
495
496 Address = string()
497 IPv6Address = ip_address()
498
499 Parses an IPv6 address string and returns an ip6_address(). Does
500 not accept IPv4 addresses.
501
502 parse_strict_address(Address) -> {ok, IPAddress} | {error, einval}
503
504 Types:
505
506 Address = string()
507 IPAddress = ip_address()
508
509 Parses an IPv4 or IPv6 address string and returns an
510 ip4_address() or ip6_address(). Does not accept a shortened IPv4
511 address string.
512
513 peername(Socket :: socket()) ->
514 {ok,
515 {ip_address(), port_number()} |
516 returned_non_ip_address()} |
517 {error, posix()}
518
519 Returns the address and port for the other end of a connection.
520
521 Notice that for SCTP sockets, this function returns only one of
522 the peer addresses of the socket. Function peernames/1,2 returns
523 all.
524
525 peernames(Socket :: socket()) ->
526 {ok,
527 [{ip_address(), port_number()} |
528 returned_non_ip_address()]} |
529 {error, posix()}
530
531 Equivalent to peernames(Socket, 0).
532
533 Notice that the behavior of this function for an SCTP one-to-
534 many style socket is not defined by the SCTP Sockets API Exten‐
535 sions.
536
537 peernames(Socket, Assoc) ->
538 {ok, [{Address, Port}]} | {error, posix()}
539
540 Types:
541
542 Socket = socket()
543 Assoc = #sctp_assoc_change{} | gen_sctp:assoc_id()
544 Address = ip_address()
545 Port = integer() >= 0
546
547 Returns a list of all address/port number pairs for the other
548 end of an association Assoc of a socket.
549
550 This function can return multiple addresses for multihomed sock‐
551 ets, such as SCTP sockets. For other sockets it returns a one-
552 element list.
553
554 Notice that parameter Assoc is by the SCTP Sockets API Exten‐
555 sions defined to be ignored for one-to-one style sockets. What
556 the special value 0 means, hence its behavior for one-to-many
557 style sockets, is unfortunately undefined.
558
559 port(Socket) -> {ok, Port} | {error, any()}
560
561 Types:
562
563 Socket = socket()
564 Port = port_number()
565
566 Returns the local port number for a socket.
567
568 setopts(Socket, Options) -> ok | {error, posix()}
569
570 Types:
571
572 Socket = socket()
573 Options = [socket_setopt()]
574
575 Sets one or more options for a socket.
576
577 The following options are available:
578
579 {active, true | false | once | N}:
580 If the value is true, which is the default, everything
581 received from the socket is sent as messages to the receiv‐
582 ing process.
583
584 If the value is false (passive mode), the process must
585 explicitly receive incoming data by calling
586 gen_tcp:recv/2,3, gen_udp:recv/2,3, or gen_sctp:recv/1,2
587 (depending on the type of socket).
588
589 If the value is once ({active, once}), one data message from
590 the socket is sent to the process. To receive one more mes‐
591 sage, setopts/2 must be called again with option {active,
592 once}.
593
594 If the value is an integer N in the range -32768 to 32767
595 (inclusive), the value is added to the socket's count of
596 data messages sent to the controlling process. A socket's
597 default message count is 0. If a negative value is speci‐
598 fied, and its magnitude is equal to or greater than the
599 socket's current message count, the socket's message count
600 is set to 0. Once the socket's message count reaches 0,
601 either because of sending received data messages to the
602 process or by being explicitly set, the process is then
603 notified by a special message, specific to the type of
604 socket, that the socket has entered passive mode. Once the
605 socket enters passive mode, to receive more messages
606 setopts/2 must be called again to set the socket back into
607 an active mode.
608
609 When using {active, once} or {active, N}, the socket changes
610 behavior automatically when data is received. This can be
611 confusing in combination with connection-oriented sockets
612 (that is, gen_tcp), as a socket with {active, false} behav‐
613 ior reports closing differently than a socket with {active,
614 true} behavior. To simplify programming, a socket where the
615 peer closed, and this is detected while in {active, false}
616 mode, still generates message {tcp_closed,Socket} when set
617 to {active, once}, {active, true}, or {active, N} mode. It
618 is therefore safe to assume that message
619 {tcp_closed,Socket}, possibly followed by socket port termi‐
620 nation (depending on option exit_on_close) eventually
621 appears when a socket changes back and forth between
622 {active, true} and {active, false} mode. However, when peer
623 closing is detected it is all up to the underlying TCP/IP
624 stack and protocol.
625
626 Notice that {active, true} mode provides no flow control; a
627 fast sender can easily overflow the receiver with incoming
628 messages. The same is true for {active, N} mode, while the
629 message count is greater than zero.
630
631 Use active mode only if your high-level protocol provides
632 its own flow control (for example, acknowledging received
633 messages) or the amount of data exchanged is small. {active,
634 false} mode, use of the {active, once} mode, or {active, N}
635 mode with values of N appropriate for the application pro‐
636 vides flow control. The other side cannot send faster than
637 the receiver can read.
638
639 {broadcast, Boolean} (UDP sockets):
640 Enables/disables permission to send broadcasts.
641
642 {buffer, Size}:
643 The size of the user-level software buffer used by the
644 driver. Not to be confused with options sndbuf and recbuf,
645 which correspond to the Kernel socket buffers. It is recom‐
646 mended to have val(buffer) >= max(val(sndbuf),val(recbuf))
647 to avoid performance issues because of unnecessary copying.
648 val(buffer) is automatically set to the above maximum when
649 values sndbuf or recbuf are set. However, as the sizes set
650 for sndbuf and recbuf usually become larger, you are encour‐
651 aged to use getopts/2 to analyze the behavior of your oper‐
652 ating system.
653
654 Note that this is also the maximum amount of data that can
655 be received from a single recv call. If you are using higher
656 than normal MTU consider setting buffer higher.
657
658 {delay_send, Boolean}:
659 Normally, when an Erlang process sends to a socket, the
660 driver tries to send the data immediately. If that fails,
661 the driver uses any means available to queue up the message
662 to be sent whenever the operating system says it can handle
663 it. Setting {delay_send, true} makes all messages queue up.
664 The messages sent to the network are then larger but fewer.
665 The option affects the scheduling of send requests versus
666 Erlang processes instead of changing any real property of
667 the socket. The option is implementation-specific. Defaults
668 to false.
669
670 {deliver, port | term}:
671 When {active, true}, data is delivered on the form port :
672 {S, {data, [H1,..Hsz | Data]}} or term : {tcp, S, [H1..Hsz |
673 Data]}.
674
675 {dontroute, Boolean}:
676 Enables/disables routing bypass for outgoing messages.
677
678 {exit_on_close, Boolean}:
679 This option is set to true by default.
680
681 The only reason to set it to false is if you want to con‐
682 tinue sending data to the socket after a close is detected,
683 for example, if the peer uses gen_tcp:shutdown/2 to shut
684 down the write side.
685
686 {header, Size}:
687 This option is only meaningful if option binary was speci‐
688 fied when the socket was created. If option header is speci‐
689 fied, the first Size number bytes of data received from the
690 socket are elements of a list, and the remaining data is a
691 binary specified as the tail of the same list. For example,
692 if Size == 2, the data received matches
693 [Byte1,Byte2|Binary].
694
695 {high_msgq_watermark, Size}:
696 The socket message queue is set to a busy state when the
697 amount of data on the message queue reaches this limit.
698 Notice that this limit only concerns data that has not yet
699 reached the ERTS internal socket implementation. Defaults to
700 8 kB.
701
702 Senders of data to the socket are suspended if either the
703 socket message queue is busy or the socket itself is busy.
704
705 For more information, see options low_msgq_watermark,
706 high_watermark, and low_watermark.
707
708 Notice that distribution sockets disable the use of
709 high_msgq_watermark and low_msgq_watermark. Instead use the
710 distribution buffer busy limit, which is a similar feature.
711
712 {high_watermark, Size} (TCP/IP sockets):
713 The socket is set to a busy state when the amount of data
714 queued internally by the ERTS socket implementation reaches
715 this limit. Defaults to 8 kB.
716
717 Senders of data to the socket are suspended if either the
718 socket message queue is busy or the socket itself is busy.
719
720 For more information, see options low_watermark,
721 high_msgq_watermark, and low_msqg_watermark.
722
723 {ipv6_v6only, Boolean}:
724 Restricts the socket to use only IPv6, prohibiting any IPv4
725 connections. This is only applicable for IPv6 sockets
726 (option inet6).
727
728 On most platforms this option must be set on the socket
729 before associating it to an address. It is therefore only
730 reasonable to specify it when creating the socket and not to
731 use it when calling function (setopts/2) containing this
732 description.
733
734 The behavior of a socket with this option set to true is the
735 only portable one. The original idea when IPv6 was new of
736 using IPv6 for all traffic is now not recommended by FreeBSD
737 (you can use {ipv6_v6only,false} to override the recommended
738 system default value), forbidden by OpenBSD (the supported
739 GENERIC kernel), and impossible on Windows (which has sepa‐
740 rate IPv4 and IPv6 protocol stacks). Most Linux distros
741 still have a system default value of false. This policy
742 shift among operating systems to separate IPv6 from IPv4
743 traffic has evolved, as it gradually proved hard and compli‐
744 cated to get a dual stack implementation correct and secure.
745
746 On some platforms, the only allowed value for this option is
747 true, for example, OpenBSD and Windows. Trying to set this
748 option to false, when creating the socket, fails in this
749 case.
750
751 Setting this option on platforms where it does not exist is
752 ignored. Getting this option with getopts/2 returns no
753 value, that is, the returned list does not contain an
754 {ipv6_v6only,_} tuple. On Windows, the option does not
755 exist, but it is emulated as a read-only option with value
756 true.
757
758 Therefore, setting this option to true when creating a
759 socket never fails, except possibly on a platform where you
760 have customized the kernel to only allow false, which can be
761 doable (but awkward) on, for example, OpenBSD.
762
763 If you read back the option value using getopts/2 and get no
764 value, the option does not exist in the host operating sys‐
765 tem. The behavior of both an IPv6 and an IPv4 socket listen‐
766 ing on the same port, and for an IPv6 socket getting IPv4
767 traffic is then no longer predictable.
768
769 {keepalive, Boolean}(TCP/IP sockets):
770 Enables/disables periodic transmission on a connected socket
771 when no other data is exchanged. If the other end does not
772 respond, the connection is considered broken and an error
773 message is sent to the controlling process. Defaults to dis‐
774 abled.
775
776 {linger, {true|false, Seconds}}:
777 Determines the time-out, in seconds, for flushing unsent
778 data in the close/1 socket call. If the first component of
779 the value tuple is false, the second is ignored. This means
780 that close/1 returns immediately, not waiting for data to be
781 flushed. Otherwise, the second component is the flushing
782 time-out, in seconds.
783
784 {low_msgq_watermark, Size}:
785 If the socket message queue is in a busy state, the socket
786 message queue is set in a not busy state when the amount of
787 data queued in the message queue falls below this limit.
788 Notice that this limit only concerns data that has not yet
789 reached the ERTS internal socket implementation. Defaults to
790 4 kB.
791
792 Senders that are suspended because of either a busy message
793 queue or a busy socket are resumed when the socket message
794 queue and the socket are not busy.
795
796 For more information, see options high_msgq_watermark,
797 high_watermark, and low_watermark.
798
799 Notice that distribution sockets disable the use of
800 high_msgq_watermark and low_msgq_watermark. Instead they use
801 the distribution buffer busy limit, which is a similar fea‐
802 ture.
803
804 {low_watermark, Size} (TCP/IP sockets):
805 If the socket is in a busy state, the socket is set in a not
806 busy state when the amount of data queued internally by the
807 ERTS socket implementation falls below this limit. Defaults
808 to 4 kB.
809
810 Senders that are suspended because of a busy message queue
811 or a busy socket are resumed when the socket message queue
812 and the socket are not busy.
813
814 For more information, see options high_watermark,
815 high_msgq_watermark, and low_msgq_watermark.
816
817 {mode, Mode :: binary | list}:
818 Received Packet is delivered as defined by Mode.
819
820 {netns, Namespace :: file:filename_all()}:
821 Sets a network namespace for the socket. Parameter Namespace
822 is a filename defining the namespace, for example,
823 "/var/run/netns/example", typically created by command ip
824 netns add example. This option must be used in a function
825 call that creates a socket, that is, gen_tcp:connect/3,4,
826 gen_tcp:listen/2, gen_udp:open/1,2, or gen_sctp:open/0,1,2.
827
828 This option uses the Linux-specific syscall setns(), such as
829 in Linux kernel 3.0 or later, and therefore only exists when
830 the runtime system is compiled for such an operating system.
831
832 The virtual machine also needs elevated privileges, either
833 running as superuser or (for Linux) having capability
834 CAP_SYS_ADMIN according to the documentation for setns(2).
835 However, during testing also CAP_SYS_PTRACE and
836 CAP_DAC_READ_SEARCH have proven to be necessary.
837
838 Example:
839
840 setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp
841
842 Notice that the filesystem containing the virtual machine
843 executable (beam.smp in the example) must be local, mounted
844 without flag nosetuid, support extended attributes, and the
845 kernel must support file capabilities. All this runs out of
846 the box on at least Ubuntu 12.04 LTS, except that SCTP sock‐
847 ets appear to not support network namespaces.
848
849 Namespace is a filename and is encoded and decoded as dis‐
850 cussed in module file, with the following exceptions:
851
852 * Emulator flag +fnu is ignored.
853
854 * getopts/2 for this option returns a binary for the file‐
855 name if the stored filename cannot be decoded. This is
856 only to occur if you set the option using a binary that
857 cannot be decoded with the emulator's filename encoding:
858 file:native_name_encoding/0.
859
860 {bind_to_device, Ifname :: binary()}:
861 Binds a socket to a specific network interface. This option
862 must be used in a function call that creates a socket, that
863 is, gen_tcp:connect/3,4, gen_tcp:listen/2, gen_udp:open/1,2,
864 or gen_sctp:open/0,1,2.
865
866 Unlike getifaddrs/0, Ifname is encoded a binary. In the
867 unlikely case that a system is using non-7-bit-ASCII charac‐
868 ters in network device names, special care has to be taken
869 when encoding this argument.
870
871 This option uses the Linux-specific socket option SO_BIND‐
872 TODEVICE, such as in Linux kernel 2.0.30 or later, and
873 therefore only exists when the runtime system is compiled
874 for such an operating system.
875
876 Before Linux 3.8, this socket option could be set, but could
877 not retrieved with getopts/2. Since Linux 3.8, it is read‐
878 able.
879
880 The virtual machine also needs elevated privileges, either
881 running as superuser or (for Linux) having capability
882 CAP_NET_RAW.
883
884 The primary use case for this option is to bind sockets into
885 Linux VRF instances.
886
887 list:
888 Received Packet is delivered as a list.
889
890 binary:
891 Received Packet is delivered as a binary.
892
893 {nodelay, Boolean}(TCP/IP sockets):
894 If Boolean == true, option TCP_NODELAY is turned on for the
895 socket, which means that also small amounts of data are sent
896 immediately.
897
898 {packet, PacketType}(TCP/IP sockets):
899 Defines the type of packets to use for a socket. Possible
900 values:
901
902 raw | 0:
903 No packaging is done.
904
905 1 | 2 | 4:
906 Packets consist of a header specifying the number of bytes
907 in the packet, followed by that number of bytes. The
908 header length can be one, two, or four bytes, and contain‐
909 ing an unsigned integer in big-endian byte order. Each
910 send operation generates the header, and the header is
911 stripped off on each receive operation.
912
913 The 4-byte header is limited to 2Gb.
914
915 asn1 | cdr | sunrm | fcgi | tpkt | line:
916 These packet types only have effect on receiving. When
917 sending a packet, it is the responsibility of the applica‐
918 tion to supply a correct header. On receiving, however,
919 one message is sent to the controlling process for each
920 complete packet received, and, similarly, each call to
921 gen_tcp:recv/2,3 returns one complete packet. The header
922 is not stripped off.
923
924 The meanings of the packet types are as follows:
925
926 * asn1 - ASN.1 BER
927
928 * sunrm - Sun's RPC encoding
929
930 * cdr - CORBA (GIOP 1.1)
931
932 * fcgi - Fast CGI
933
934 * tpkt - TPKT format [RFC1006]
935
936 * line - Line mode, a packet is a line-terminated with
937 newline, lines longer than the receive buffer are trun‐
938 cated
939
940 http | http_bin:
941 The Hypertext Transfer Protocol. The packets are returned
942 with the format according to HttpPacket described in
943 erlang:decode_packet/3 in ERTS. A socket in passive mode
944 returns {ok, HttpPacket} from gen_tcp:recv while an active
945 socket sends messages like {http, Socket, HttpPacket}.
946
947 httph | httph_bin:
948 These two types are often not needed, as the socket auto‐
949 matically switches from http/http_bin to httph/httph_bin
950 internally after the first line is read. However, there
951 can be occasions when they are useful, such as parsing
952 trailers from chunked encoding.
953
954 {packet_size, Integer}(TCP/IP sockets):
955 Sets the maximum allowed length of the packet body. If the
956 packet header indicates that the length of the packet is
957 longer than the maximum allowed length, the packet is con‐
958 sidered invalid. The same occurs if the packet header is too
959 large for the socket receive buffer.
960
961 For line-oriented protocols (line, http*), option
962 packet_size also guarantees that lines up to the indicated
963 length are accepted and not considered invalid because of
964 internal buffer limitations.
965
966 {line_delimiter, Char}(TCP/IP sockets):
967 Sets the line delimiting character for line-oriented proto‐
968 cols (line). Defaults to $\n.
969
970 {raw, Protocol, OptionNum, ValueBin}:
971 See below.
972
973 {read_packets, Integer}(UDP sockets):
974 Sets the maximum number of UDP packets to read without
975 intervention from the socket when data is available. When
976 this many packets have been read and delivered to the desti‐
977 nation process, new packets are not read until a new notifi‐
978 cation of available data has arrived. Defaults to 5. If this
979 parameter is set too high, the system can become unrespon‐
980 sive because of UDP packet flooding.
981
982 {recbuf, Size}:
983 The minimum size of the receive buffer to use for the
984 socket. You are encouraged to use getopts/2 to retrieve the
985 size set by your operating system.
986
987 {reuseaddr, Boolean}:
988 Allows or disallows local reuse of port numbers. By default,
989 reuse is disallowed.
990
991 {send_timeout, Integer}:
992 Only allowed for connection-oriented sockets.
993
994 Specifies a longest time to wait for a send operation to be
995 accepted by the underlying TCP stack. When the limit is
996 exceeded, the send operation returns {error,timeout}. How
997 much of a packet that got sent is unknown; the socket is
998 therefore to be closed whenever a time-out has occurred (see
999 send_timeout_close below). Defaults to infinity.
1000
1001 {send_timeout_close, Boolean}:
1002 Only allowed for connection-oriented sockets.
1003
1004 Used together with send_timeout to specify whether the
1005 socket is to be automatically closed when the send operation
1006 returns {error,timeout}. The recommended setting is true,
1007 which automatically closes the socket. Defaults to false
1008 because of backward compatibility.
1009
1010 {show_econnreset, Boolean}(TCP/IP sockets):
1011 When this option is set to false, which is default, an RST
1012 received from the TCP peer is treated as a normal close (as
1013 though an FIN was sent). A caller to gen_tcp:recv/2 gets
1014 {error, closed}. In active mode, the controlling process
1015 receives a {tcp_close, Socket} message, indicating that the
1016 peer has closed the connection.
1017
1018 Setting this option to true allows you to distinguish
1019 between a connection that was closed normally, and one that
1020 was aborted (intentionally or unintentionally) by the TCP
1021 peer. A call to gen_tcp:recv/2 returns {error, econnreset}.
1022 In active mode, the controlling process receives a
1023 {tcp_error, Socket, econnreset} message before the usual
1024 {tcp_closed, Socket}, as is the case for any other socket
1025 error. Calls to gen_tcp:send/2 also returns {error, econnre‐
1026 set} when it is detected that a TCP peer has sent an RST.
1027
1028 A connected socket returned from gen_tcp:accept/1 inherits
1029 the show_econnreset setting from the listening socket.
1030
1031 {sndbuf, Size}:
1032 The minimum size of the send buffer to use for the socket.
1033 You are encouraged to use getopts/2, to retrieve the size
1034 set by your operating system.
1035
1036 {priority, Integer}:
1037 Sets the SO_PRIORITY socket level option on platforms where
1038 this is implemented. The behavior and allowed range varies
1039 between different systems. The option is ignored on plat‐
1040 forms where it is not implemented. Use with caution.
1041
1042 {tos, Integer}:
1043 Sets IP_TOS IP level options on platforms where this is
1044 implemented. The behavior and allowed range varies between
1045 different systems. The option is ignored on platforms where
1046 it is not implemented. Use with caution.
1047
1048 {tclass, Integer}:
1049 Sets IPV6_TCLASS IP level options on platforms where this is
1050 implemented. The behavior and allowed range varies between
1051 different systems. The option is ignored on platforms where
1052 it is not implemented. Use with caution.
1053
1054 In addition to these options, raw option specifications can be
1055 used. The raw options are specified as a tuple of arity four,
1056 beginning with tag raw, followed by the protocol level, the
1057 option number, and the option value specified as a binary. This
1058 corresponds to the second, third, and fourth arguments to the
1059 setsockopt call in the C socket API. The option value must be
1060 coded in the native endianess of the platform and, if a struc‐
1061 ture is required, must follow the structure alignment conven‐
1062 tions on the specific platform.
1063
1064 Using raw socket options requires detailed knowledge about the
1065 current operating system and TCP stack.
1066
1067 Example:
1068
1069 This example concerns the use of raw options. Consider a Linux
1070 system where you want to set option TCP_LINGER2 on protocol
1071 level IPPROTO_TCP in the stack. You know that on this particular
1072 system it defaults to 60 (seconds), but you want to lower it to
1073 30 for a particular socket. Option TCP_LINGER2 is not explicitly
1074 supported by inet, but you know that the protocol level trans‐
1075 lates to number 6, the option number to number 8, and the value
1076 is to be specified as a 32-bit integer. You can use this code
1077 line to set the option for the socket named Sock:
1078
1079 inet:setopts(Sock,[{raw,6,8,<<30:32/native>>}]),
1080
1081 As many options are silently discarded by the stack if they are
1082 specified out of range; it can be a good idea to check that a
1083 raw option is accepted. The following code places the value in
1084 variable TcpLinger2:
1085
1086 {ok,[{raw,6,8,<<TcpLinger2:32/native>>}]}=inet:getopts(Sock,[{raw,6,8,4}]),
1087
1088 Code such as these examples is inherently non-portable, even
1089 different versions of the same OS on the same platform can
1090 respond differently to this kind of option manipulation. Use
1091 with care.
1092
1093 Notice that the default options for TCP/IP sockets can be
1094 changed with the Kernel configuration parameters mentioned in
1095 the beginning of this manual page.
1096
1097 sockname(Socket :: socket()) ->
1098 {ok,
1099 {ip_address(), port_number()} |
1100 returned_non_ip_address()} |
1101 {error, posix()}
1102
1103 Returns the local address and port number for a socket.
1104
1105 Notice that for SCTP sockets this function returns only one of
1106 the socket addresses. Function socknames/1,2 returns all.
1107
1108 socknames(Socket :: socket()) ->
1109 {ok,
1110 [{ip_address(), port_number()} |
1111 returned_non_ip_address()]} |
1112 {error, posix()}
1113
1114 Equivalent to socknames(Socket, 0).
1115
1116 socknames(Socket, Assoc) ->
1117 {ok, [{Address, Port}]} | {error, posix()}
1118
1119 Types:
1120
1121 Socket = socket()
1122 Assoc = #sctp_assoc_change{} | gen_sctp:assoc_id()
1123 Address = ip_address()
1124 Port = integer() >= 0
1125
1126 Returns a list of all local address/port number pairs for a
1127 socket for the specified association Assoc.
1128
1129 This function can return multiple addresses for multihomed sock‐
1130 ets, such as SCTP sockets. For other sockets it returns a one-
1131 element list.
1132
1133 Notice that parameter Assoc is by the SCTP Sockets API Exten‐
1134 sions defined to be ignored for one-to-one style sockets. For
1135 one-to-many style sockets, the special value 0 is defined to
1136 mean that the returned addresses must be without any particular
1137 association. How different SCTP implementations interprets this
1138 varies somewhat.
1139
1141 * e2big - Too long argument list
1142
1143 * eacces - Permission denied
1144
1145 * eaddrinuse - Address already in use
1146
1147 * eaddrnotavail - Cannot assign requested address
1148
1149 * eadv - Advertise error
1150
1151 * eafnosupport - Address family not supported by protocol family
1152
1153 * eagain - Resource temporarily unavailable
1154
1155 * ealign - EALIGN
1156
1157 * ealready - Operation already in progress
1158
1159 * ebade - Bad exchange descriptor
1160
1161 * ebadf - Bad file number
1162
1163 * ebadfd - File descriptor in bad state
1164
1165 * ebadmsg - Not a data message
1166
1167 * ebadr - Bad request descriptor
1168
1169 * ebadrpc - Bad RPC structure
1170
1171 * ebadrqc - Bad request code
1172
1173 * ebadslt - Invalid slot
1174
1175 * ebfont - Bad font file format
1176
1177 * ebusy - File busy
1178
1179 * echild - No children
1180
1181 * echrng - Channel number out of range
1182
1183 * ecomm - Communication error on send
1184
1185 * econnaborted - Software caused connection abort
1186
1187 * econnrefused - Connection refused
1188
1189 * econnreset - Connection reset by peer
1190
1191 * edeadlk - Resource deadlock avoided
1192
1193 * edeadlock - Resource deadlock avoided
1194
1195 * edestaddrreq - Destination address required
1196
1197 * edirty - Mounting a dirty fs without force
1198
1199 * edom - Math argument out of range
1200
1201 * edotdot - Cross mount point
1202
1203 * edquot - Disk quota exceeded
1204
1205 * eduppkg - Duplicate package name
1206
1207 * eexist - File already exists
1208
1209 * efault - Bad address in system call argument
1210
1211 * efbig - File too large
1212
1213 * ehostdown - Host is down
1214
1215 * ehostunreach - Host is unreachable
1216
1217 * eidrm - Identifier removed
1218
1219 * einit - Initialization error
1220
1221 * einprogress - Operation now in progress
1222
1223 * eintr - Interrupted system call
1224
1225 * einval - Invalid argument
1226
1227 * eio - I/O error
1228
1229 * eisconn - Socket is already connected
1230
1231 * eisdir - Illegal operation on a directory
1232
1233 * eisnam - Is a named file
1234
1235 * el2hlt - Level 2 halted
1236
1237 * el2nsync - Level 2 not synchronized
1238
1239 * el3hlt - Level 3 halted
1240
1241 * el3rst - Level 3 reset
1242
1243 * elbin - ELBIN
1244
1245 * elibacc - Cannot access a needed shared library
1246
1247 * elibbad - Accessing a corrupted shared library
1248
1249 * elibexec - Cannot exec a shared library directly
1250
1251 * elibmax - Attempting to link in more shared libraries than system
1252 limit
1253
1254 * elibscn - .lib section in a.out corrupted
1255
1256 * elnrng - Link number out of range
1257
1258 * eloop - Too many levels of symbolic links
1259
1260 * emfile - Too many open files
1261
1262 * emlink - Too many links
1263
1264 * emsgsize - Message too long
1265
1266 * emultihop - Multihop attempted
1267
1268 * enametoolong - Filename too long
1269
1270 * enavail - Unavailable
1271
1272 * enet - ENET
1273
1274 * enetdown - Network is down
1275
1276 * enetreset - Network dropped connection on reset
1277
1278 * enetunreach - Network is unreachable
1279
1280 * enfile - File table overflow
1281
1282 * enoano - Anode table overflow
1283
1284 * enobufs - No buffer space available
1285
1286 * enocsi - No CSI structure available
1287
1288 * enodata - No data available
1289
1290 * enodev - No such device
1291
1292 * enoent - No such file or directory
1293
1294 * enoexec - Exec format error
1295
1296 * enolck - No locks available
1297
1298 * enolink - Link has been severed
1299
1300 * enomem - Not enough memory
1301
1302 * enomsg - No message of desired type
1303
1304 * enonet - Machine is not on the network
1305
1306 * enopkg - Package not installed
1307
1308 * enoprotoopt - Bad protocol option
1309
1310 * enospc - No space left on device
1311
1312 * enosr - Out of stream resources or not a stream device
1313
1314 * enosym - Unresolved symbol name
1315
1316 * enosys - Function not implemented
1317
1318 * enotblk - Block device required
1319
1320 * enotconn - Socket is not connected
1321
1322 * enotdir - Not a directory
1323
1324 * enotempty - Directory not empty
1325
1326 * enotnam - Not a named file
1327
1328 * enotsock - Socket operation on non-socket
1329
1330 * enotsup - Operation not supported
1331
1332 * enotty - Inappropriate device for ioctl
1333
1334 * enotuniq - Name not unique on network
1335
1336 * enxio - No such device or address
1337
1338 * eopnotsupp - Operation not supported on socket
1339
1340 * eperm - Not owner
1341
1342 * epfnosupport - Protocol family not supported
1343
1344 * epipe - Broken pipe
1345
1346 * eproclim - Too many processes
1347
1348 * eprocunavail - Bad procedure for program
1349
1350 * eprogmismatch - Wrong program version
1351
1352 * eprogunavail - RPC program unavailable
1353
1354 * eproto - Protocol error
1355
1356 * eprotonosupport - Protocol not supported
1357
1358 * eprototype - Wrong protocol type for socket
1359
1360 * erange - Math result unrepresentable
1361
1362 * erefused - EREFUSED
1363
1364 * eremchg - Remote address changed
1365
1366 * eremdev - Remote device
1367
1368 * eremote - Pathname hit remote filesystem
1369
1370 * eremoteio - Remote I/O error
1371
1372 * eremoterelease - EREMOTERELEASE
1373
1374 * erofs - Read-only filesystem
1375
1376 * erpcmismatch - Wrong RPC version
1377
1378 * erremote - Object is remote
1379
1380 * eshutdown - Cannot send after socket shutdown
1381
1382 * esocktnosupport - Socket type not supported
1383
1384 * espipe - Invalid seek
1385
1386 * esrch - No such process
1387
1388 * esrmnt - Srmount error
1389
1390 * estale - Stale remote file handle
1391
1392 * esuccess - Error 0
1393
1394 * etime - Timer expired
1395
1396 * etimedout - Connection timed out
1397
1398 * etoomanyrefs - Too many references
1399
1400 * etxtbsy - Text file or pseudo-device busy
1401
1402 * euclean - Structure needs cleaning
1403
1404 * eunatch - Protocol driver not attached
1405
1406 * eusers - Too many users
1407
1408 * eversion - Version mismatch
1409
1410 * ewouldblock - Operation would block
1411
1412 * exdev - Cross-domain link
1413
1414 * exfull - Message tables full
1415
1416 * nxdomain - Hostname or domain name cannot be found
1417
1418Ericsson AB kernel 5.4.3.2 inet(3)