<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">
<erlref>
<header>
<copyright>
<year>1997</year><year>2013</year>
<holder>Ericsson AB. All Rights Reserved.</holder>
</copyright>
<legalnotice>
The contents of this file are subject to the Erlang Public License,
Version 1.1, (the "License"); you may not use this file except in
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at http://www.erlang.org/.
Software distributed under the License is distributed on an "AS IS"
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
</legalnotice>
<title>inet</title>
<prepared>[email protected]</prepared>
<docno></docno>
<date>1998-02-04</date>
<rev>A</rev>
</header>
<module>inet</module>
<modulesummary>Access to TCP/IP Protocols</modulesummary>
<description>
<p>Provides access to TCP/IP protocols.</p>
<p>See also <em>ERTS User's Guide, Inet configuration</em> for more
information on how to configure an Erlang runtime system for IP
communication.</p>
<p>Two Kernel configuration parameters affect the behaviour of all
sockets opened on an Erlang node:
<c>inet_default_connect_options</c> can contain a list of default
options used for all sockets returned when doing <c>connect</c>,
and <c>inet_default_listen_options</c> can contain a list of
default options used when issuing a <c>listen</c> call. When
<c>accept</c> is issued, the values of the listensocket options
are inherited, why no such application variable is needed for
<c>accept</c>.</p>
<p>Using the Kernel configuration parameters mentioned above, one
can set default options for all TCP sockets on a node. This should
be used with care, but options like <c>{delay_send,true}</c>
might be specified in this way. An example of starting an Erlang
node with all sockets using delayed send could look like this:</p>
<pre>
$ <input>erl -sname test -kernel \</input>
<input>inet_default_connect_options '[{delay_send,true}]' \</input>
<input>inet_default_listen_options '[{delay_send,true}]'</input></pre>
<p>Note that the default option <c>{active, true}</c> currently
cannot be changed, for internal reasons.</p>
<p>Addresses as inputs to functions can be either a string or a
tuple. For instance, the IP address 150.236.20.73 can be passed to
<c>gethostbyaddr/1</c> either as the string "150.236.20.73"
or as the tuple <c>{150, 236, 20, 73}</c>.</p>
<p>IPv4 address examples:</p>
<code type="none">
Address ip_address()
------- ------------
127.0.0.1 {127,0,0,1}
192.168.42.2 {192,168,42,2}</code>
<p>IPv6 address examples:</p>
<code type="none">
Address ip_address()
------- ------------
::1 {0,0,0,0,0,0,0,1}
::192.168.42.2 {0,0,0,0,0,0,(192 bsl 8) bor 168,(42 bsl 8) bor 2}
FFFF::192.168.42.2
{16#FFFF,0,0,0,0,0,(192 bsl 8) bor 168,(42 bsl 8) bor 2}
3ffe:b80:1f8d:2:204:acff:fe17:bf38
{16#3ffe,16#b80,16#1f8d,16#2,16#204,16#acff,16#fe17,16#bf38}
fe80::204:acff:fe17:bf38
{16#fe80,0,0,0,0,16#204,16#acff,16#fe17,16#bf38}</code>
<p>A function that may be useful is <seealso marker="#parse_address/1">parse_address/1</seealso>:</p>
<pre>
1> <input>inet:parse_address("192.168.42.2").</input>
{ok,{192,168,42,2}}
2> <input>inet:parse_address("FFFF::192.168.42.2").</input>
{ok,{65535,0,0,0,0,0,49320,10754}}</pre>
</description>
<datatypes>
<datatype>
<name name="hostent"/>
<desc>
<p>The record is defined in the Kernel include file "inet.hrl".
Add the following directive to the module:</p>
<code>-include_lib("kernel/include/inet.hrl").</code></desc>
</datatype>
<datatype>
<name name="hostname"/>
</datatype>
<datatype>
<name name="ip_address"/>
</datatype>
<datatype>
<name name="ip4_address"/>
</datatype>
<datatype>
<name name="ip6_address"/>
</datatype>
<datatype>
<name name="port_number"/>
</datatype>
<datatype>
<name name="posix"/>
<desc><p>An atom which is named from the Posix error codes
used in Unix, and in the runtime libraries of most
C compilers. See
<seealso marker="#error_codes">POSIX Error Codes</seealso>.</p>
</desc>
</datatype>
<datatype>
<name><marker id="type-socket">socket()</marker></name>
<desc><p>See <seealso marker="gen_tcp#type-socket">gen_tcp(3)</seealso>
and <seealso marker="gen_udp#type-socket">gen_udp(3)</seealso>.</p>
</desc>
</datatype>
<datatype>
<name name="address_family"/>
</datatype>
</datatypes>
<funcs>
<func>
<name name="close" arity="1"/>
<fsummary>Close a socket of any type</fsummary>
<desc>
<p>Closes a socket of any type.</p>
</desc>
</func>
<func>
<name name="get_rc" arity="0"/>
<fsummary>Return a list of IP configuration parameters</fsummary>
<desc>
<p>Returns the state of the Inet configuration database in
form of a list of recorded configuration parameters. (See the
ERTS User's Guide, Inet configuration, for more information).
Only parameters with other than default values are returned.</p>
</desc>
</func>
<func>
<name name="format_error" arity="1"/>
<fsummary>Return a descriptive string for an error reason</fsummary>
<desc>
<p>Returns a diagnostic error string. See the section below
for possible Posix values and the corresponding
strings.</p>
</desc>
</func>
<func>
<name name="getaddr" arity="2"/>
<fsummary>Return the IP-address for a host</fsummary>
<desc>
<p>Returns the IP-address for <c><anno>Host</anno></c> as a tuple of
integers. <c><anno>Host</anno></c> can be an IP-address, a single hostname
or a fully qualified hostname.</p>
</desc>
</func>
<func>
<name name="getaddrs" arity="2"/>
<fsummary>Return the IP-addresses for a host</fsummary>
<desc>
<p>Returns a list of all IP-addresses for <c><anno>Host</anno></c>.
<c><anno>Host</anno></c> can be an IP-address, a single hostname or a fully
qualified hostname.</p>
</desc>
</func>
<func>
<name name="gethostbyaddr" arity="1"/>
<fsummary>Return a hostent record for the host with the given address</fsummary>
<desc>
<p>Returns a <c>hostent</c> record given an address.</p>
</desc>
</func>
<func>
<name name="gethostbyname" arity="1"/>
<fsummary>Return a hostent record for the host with the given name</fsummary>
<desc>
<p>Returns a <c>hostent</c> record given a hostname.</p>
</desc>
</func>
<func>
<name name="gethostbyname" arity="2"/>
<fsummary>Return a hostent record for the host with the given name</fsummary>
<desc>
<p>Returns a <c>hostent</c> record given a hostname, restricted
to the given address family.</p>
</desc>
</func>
<func>
<name name="gethostname" arity="0"/>
<fsummary>Return the local hostname</fsummary>
<desc>
<p>Returns the local hostname. Will never fail.</p>
</desc>
</func>
<func>
<name name="getifaddrs" arity="0"/>
<fsummary>Return a list of interfaces and their addresses</fsummary>
<desc>
<p>
Returns a list of 2-tuples containing interface names and the
interface's addresses. <c><anno>Ifname</anno></c> is a Unicode string.
<c><anno>Hwaddr</anno></c> is hardware dependent, e.g on Ethernet interfaces
it is the 6-byte Ethernet address (MAC address (EUI-48 address)).
</p>
<p>
The <c>{addr,<anno>Addr</anno>}</c>, <c>{netmask,_}</c> and <c>{broadaddr,_}</c>
tuples are repeated in the result list iff the interface has multiple
addresses. If you come across an interface that has
multiple <c>{flag,_}</c> or <c>{hwaddr,_}</c> tuples you have
a really strange interface or possibly a bug in this function.
The <c>{flag,_}</c> tuple is mandatory, all other optional.
</p>
<p>
Do not rely too much on the order of <c><anno>Flag</anno></c> atoms or
<c><anno>Ifopt</anno></c> tuples. There are some rules, though:
<list>
<item>
Immediately after <c>{addr,_}</c> follows <c>{netmask,_}</c>
</item>
<item>
Immediately thereafter follows <c>{broadaddr,_}</c> if
the <c>broadcast</c> flag is <em>not</em> set and the
<c>pointtopoint</c> flag <em>is</em> set.
</item>
<item>
Any <c>{netmask,_}</c>, <c>{broadaddr,_}</c> or
<c>{dstaddr,_}</c> tuples that follow an <c>{addr,_}</c>
tuple concerns that address.
</item>
</list>
</p>
<p>
The <c>{hwaddr,_}</c> tuple is not returned on Solaris since the
hardware address historically belongs to the link layer and only
the superuser can read such addresses.
</p>
<p>
On Windows, the data is fetched from quite different OS API
functions, so the <c><anno>Netmask</anno></c> and <c><anno>Broadaddr</anno></c>
values may be calculated, just as some <c><anno>Flag</anno></c> values.
You have been warned. Report flagrant bugs.
</p>
</desc>
</func>
<func>
<name name="getopts" arity="2"/>
<fsummary>Get one or more options for a socket</fsummary>
<type name="socket_getopt"/>
<type name="socket_setopt"/>
<desc>
<p>Gets one or more options for a socket.
See <seealso marker="#setopts/2">setopts/2</seealso>
for a list of available options.</p>
<p>The number of elements in the returned <c><anno>OptionValues</anno></c>
list does not necessarily correspond to the number of options
asked for. If the operating system fails to support an option,
it is simply left out in the returned list. An error tuple is only
returned when getting options for the socket is impossible
(i.e. the socket is closed or the buffer size in a raw request
is too large). This behavior is kept for backward
compatibility reasons.</p>
<p>A raw option request <c>RawOptReq = {raw, Protocol, OptionNum, ValueSpec}</c> can be used to get information about
socket options not (explicitly) supported by the emulator. The
use of raw socket options makes the code non portable, but
allows the Erlang programmer to take advantage of unusual features
present on the current platform.</p>
<p>The <c>RawOptReq</c> consists of the tag <c>raw</c> followed
by the protocol level, the option number and either a binary
or the size, in bytes, of the
buffer in which the option value is to be stored. A binary
should be used when the underlying <c>getsockopt</c> requires
<em>input</em>
in the argument field, in which case the size of the binary
should correspond to the required buffer
size of the return value. The supplied values in a <c>RawOptReq</c>
correspond to the second, third and fourth/fifth parameters to the
<c>getsockopt</c> call in the C socket API. The value stored
in the buffer is returned as a binary <c>ValueBin</c>
where all values are coded in the native endianess.</p>
<p>Asking for and inspecting raw socket options require low
level information about the current operating system and TCP
stack.</p>
<p>As an example, consider a Linux machine where the
<c>TCP_INFO</c> option could be used to collect TCP statistics
for a socket. Lets say we're interested in the
<c>tcpi_sacked</c> field of the <c>struct tcp_info</c>
filled in when asking for <c>TCP_INFO</c>. To
be able to access this information, we need to know both the
numeric value of the protocol level <c>IPPROTO_TCP</c>, the
numeric value of the option <c>TCP_INFO</c>, the size of the
<c>struct tcp_info</c> and the size and offset of
the specific field. By inspecting the headers or writing a small C
program, we found <c>IPPROTO_TCP</c> to be 6,
<c>TCP_INFO</c> to be 11, the structure size to be 92 (bytes),
the offset of <c>tcpi_sacked</c> to be 28 bytes and the actual
value to be a 32 bit integer. We could use the following
code to retrieve the value:</p>
<code type="none"><![CDATA[
get_tcpi_sacked(Sock) ->
{ok,[{raw,_,_,Info}]} = inet:getopts(Sock,[{raw,6,11,92}]),
<<_:28/binary,TcpiSacked:32/native,_/binary>> = Info,
TcpiSacked.]]></code>
<p>Preferably, you would check the machine type, the OS
and the kernel version prior to executing anything similar to the
code above.</p>
</desc>
</func>
<func>
<name name="getstat" arity="1"/>
<name name="getstat" arity="2"/>
<fsummary>Get one or more statistic options for a socket</fsummary>
<type name="stat_option"/>
<desc>
<p>Gets one or more statistic options for a socket.</p>
<p><c>getstat(<anno>Socket</anno>)</c> is equivalent to
<c>getstat(<anno>Socket</anno>, [recv_avg, recv_cnt, recv_dvi,
recv_max, recv_oct, send_avg, send_cnt, send_dvi, send_max,
send_oct])</c>.</p>
<p>The following options are available:</p>
<taglist>
<tag><c>recv_avg</c></tag>
<item>
<p>Average size of packets in bytes received to the socket.</p>
</item>
<tag><c>recv_cnt</c></tag>
<item>
<p>Number of packets received to the socket.</p>
</item>
<tag><c>recv_dvi</c></tag>
<item>
<p>Average packet size deviation in bytes received to the socket.</p>
</item>
<tag><c>recv_max</c></tag>
<item>
<p>The size of the largest packet in bytes received to the socket.</p>
</item>
<tag><c>recv_oct</c></tag>
<item>
<p>Number of bytes received to the socket.</p>
</item>
<tag><c>send_avg</c></tag>
<item>
<p>Average size of packets in bytes sent from the socket.</p>
</item>
<tag><c>send_cnt</c></tag>
<item>
<p>Number of packets sent from the socket.</p>
</item>
<tag><c>send_dvi</c></tag>
<item>
<p>Average packet size deviation in bytes sent from the socket.</p>
</item>
<tag><c>send_max</c></tag>
<item>
<p>The size of the largest packet in bytes sent from the socket.</p>
</item>
<tag><c>send_oct</c></tag>
<item>
<p>Number of bytes sent from the socket.</p>
</item>
</taglist>
</desc>
</func>
<func>
<name name="ntoa" arity="1" />
<fsummary>Convert IPv6 / IPV4 adress to ascii</fsummary>
<desc>
<p>Parses an <a href="#type-ip_address">ip_address()</a> and returns an IPv4 or IPv6 address string.</p>
</desc>
</func>
<func>
<name name="parse_ipv4_address" arity="1" />
<fsummary>Parse an IPv4 address</fsummary>
<desc>
<p>Parses an IPv4 address string and returns an <a href="#type-ip4_address">ip4_address()</a>.
Accepts a shortened IPv4 shortened address string.</p>
</desc>
</func>
<func>
<name name="parse_ipv4strict_address" arity="1" />
<fsummary>Parse an IPv4 address strict.</fsummary>
<desc>
<p>Parses an IPv4 address string containing four fields, i.e <b>not</b> shortened, and returns an <a href="#type-ip4_adress">ip4_address()</a>.</p>
</desc>
</func>
<func>
<name name="parse_ipv6_address" arity="1" />
<fsummary>Parse an IPv6 address</fsummary>
<desc>
<p>Parses an IPv6 address string and returns an <a href="#type-ip6_address">ip6_address()</a>.
If an IPv4 address string is passed, an IPv4-mapped IPv6 address is returned.</p>
</desc>
</func>
<func>
<name name="parse_ipv6strict_address" arity="1" />
<fsummary>Parse an IPv6 address strict.</fsummary>
<desc>
<p>Parses an IPv6 address string and returns an <a href="#type-ip6_address">ip6_address()</a>.
Does <b>not</b> accept IPv4 adresses.</p>
</desc>
</func>
<func>
<name name="parse_address" arity="1" />
<fsummary>Parse an IPv4 or IPv6 address.</fsummary>
<desc>
<p>Parses an IPv4 or IPv6 address string and returns an <a href="#type-ip4_address">ip4_address()</a> or <a href="#type-ip6_address">ip6_address()</a>. Accepts a shortened IPv4 address string.</p>
</desc>
</func>
<func>
<name name="parse_strict_address" arity="1" />
<fsummary>Parse an IPv4 or IPv6 address strict.</fsummary>
<desc>
<p>Parses an IPv4 or IPv6 address string and returns an <a href="#type-ip4_address">ip4_address()</a> or <a href="#type-ip6_adress">ip6_address()</a>. Does <b>not</b> accept a shortened IPv4 address string.</p>
</desc>
</func>
<func>
<name name="peername" arity="1"/>
<fsummary>Return the address and port for the other end of a connection</fsummary>
<desc>
<p>
Returns the address and port for the other end of a
connection.
</p>
<p>
Note that for SCTP sockets this function only returns
one of the socket's peer addresses. The function
<seealso marker="#peernames/1">peernames/1,2</seealso>
returns all.
</p>
</desc>
</func>
<func>
<name name="peernames" arity="1"/>
<fsummary>
Return all address/port numbers for the other end of a connection
</fsummary>
<desc>
<p>
Equivalent to
<seealso marker="#peernames/2"><c>peernames(<anno>Socket</anno>, 0)</c></seealso>.
Note that this function's behaviour for an SCTP
one-to-many style socket is not defined by the
<url href="http://tools.ietf.org/html/draft-ietf-tsvwg-sctpsocket-13">SCTP Sockets API Extensions</url>.
</p>
</desc>
</func>
<func>
<name name="peernames" arity="2"/>
<fsummary>
Return all address/port numbers for the other end of a connection
</fsummary>
<desc>
<p>
Returns a list of all address/port number pairs for the other end
of a socket's association <c><anno>Assoc</anno></c>.
</p>
<p>
This function can return multiple addresses for multihomed
sockets such as SCTP sockets. For other sockets it
returns a one element list.
</p>
<p>
Note that the <c><anno>Assoc</anno></c> parameter is by the
<url href="http://tools.ietf.org/html/draft-ietf-tsvwg-sctpsocket-13">SCTP Sockets API Extensions</url>
defined to be ignored for
one-to-one style sockets. What the special value <c>0</c>
means hence its behaviour for one-to-many style sockets
is unfortunately not defined.
</p>
</desc>
</func>
<func>
<name name="port" arity="1"/>
<fsummary>Return the local port number for a socket</fsummary>
<desc>
<p>Returns the local port number for a socket.</p>
</desc>
</func>
<func>
<name name="sockname" arity="1"/>
<fsummary>Return the local address and port number for a socket</fsummary>
<desc>
<p>Returns the local address and port number for a socket.</p>
<p>
Note that for SCTP sockets this function only returns
one of the socket addresses. The function
<seealso marker="#socknames/1">socknames/1,2</seealso>
returns all.
</p>
</desc>
</func>
<func>
<name name="socknames" arity="1"/>
<fsummary>Return all local address/port numbers for a socket</fsummary>
<desc>
<p>
Equivalent to
<seealso marker="#socknames/2"><c>socknames(<anno>Socket</anno>, 0)</c></seealso>.
</p>
</desc>
</func>
<func>
<name name="socknames" arity="2"/>
<fsummary>Return all local address/port numbers for a socket</fsummary>
<desc>
<p>
Returns a list of all local address/port number pairs for a socket
for the given association <c><anno>Assoc</anno></c>.
</p>
<p>
This function can return multiple addresses for multihomed
sockets such as SCTP sockets. For other sockets it
returns a one element list.
</p>
<p>
Note that the <c><anno>Assoc</anno></c> parameter is by the
<url href="http://tools.ietf.org/html/draft-ietf-tsvwg-sctpsocket-13">SCTP Sockets API Extensions</url>
defined to be ignored for one-to-one style sockets.
For one-to-many style sockets the special value <c>0</c>
is defined to mean that the returned addresses shall be
without regard to any particular association.
How different SCTP implementations interprets this varies somewhat.
</p>
</desc>
</func>
<func>
<name name="setopts" arity="2"/>
<fsummary>Set one or more options for a socket</fsummary>
<type name="socket_setopt"/>
<desc>
<p>Sets one or more options for a socket. The following options
are available:</p>
<taglist>
<tag><c>{active, true | false | once | N}</c></tag>
<item>
<p>If the value is <c>true</c>, which is the default,
everything received from the socket will be sent as
messages to the receiving process. If the value is
<c>false</c> (passive mode), the process must explicitly
receive incoming data by calling
<seealso marker="gen_tcp#recv/2"><c>gen_tcp:recv/2,3</c></seealso>,
<seealso marker="gen_udp#recv/2"><c>gen_udp:recv/2,3</c></seealso>
or <seealso marker="gen_sctp#recv/1"><c>gen_sctp:recv/1,2</c></seealso>
(depending on the type of socket).</p>
<p>If the value is <c>once</c> (<c>{active, once}</c>),
<em>one</em> data message from the socket will be sent
to the process. To receive one more message,
<c>setopts/2</c> must be called again with the
<c>{active, once}</c> option.</p>
<p>If the value is an integer <c>N</c> in the range -32768 to 32767
(inclusive), the value is added to the socket's count of data
messages sent to the controlling process. A socket's default
message count is 0. If a negative value is specified and its
magnitude is equal to or greater than the socket's current
message count, the socket's message count is set to 0. Once
the socket's message count reaches 0, either due to sending
received data messages to the process or by being explicitly set,
the process is then notified by a special message, specific to
the type of socket, that the socket has entered passive
mode. Once the socket enters passive mode, to receive more
messages <c>setopts/2</c> must be called again to set the
socket back into an active mode.</p>
<p>When using <c>{active, once}</c> or <c>{active, N}</c>, the
socket changes behaviour automatically when data is received.
This can sometimes be confusing in combination with
connection-oriented sockets (i.e. <c>gen_tcp</c>) as a socket
with <c>{active, false}</c> behaviour reports closing
differently than a socket with <c>{active, true}</c>
behaviour. To make programming easier, a socket where
the peer closed and this was detected while in
<c>{active, false}</c> mode, will still generate the
message
<c>{tcp_closed,Socket}</c> when set to <c>{active, once}</c>,
<c>{active, true}</c> or <c>{active, N}</c> mode. It is therefore
safe to assume that the message
<c>{tcp_closed,Socket}</c>, possibly followed by socket
port termination (depending on the <c>exit_on_close</c>
option) will eventually appear when a socket changes
back and forth between <c>{active, true}</c> and
<c>{active, false}</c> mode. However,
<em>when</em> peer closing is detected is all up to the
underlying TCP/IP stack and protocol.</p>
<p>Note that <c>{active, true}</c> mode provides no flow
control; a fast sender could easily overflow the
receiver with incoming messages. The same is true of
<c>{active, N}</c> mode while the message count is greater
than zero. Use active mode only if
your high-level protocol provides its own flow control
(for instance, acknowledging received messages) or the
amount of data exchanged is small. <c>{active, false}</c>
mode, use of the <c>{active, once}</c> mode or <c>{active, N}</c>
mode with values of <c>N</c> appropriate for the application
provides flow control; the other side will not be able send
faster than the receiver can read.</p>
</item>
<tag><c>{broadcast, Boolean}</c>(UDP sockets)</tag>
<item>
<p>Enable/disable permission to send broadcasts.</p>
<marker id="option-buffer"></marker>
</item>
<tag><c>{buffer, Size}</c></tag>
<item>
<p>Determines the size of the user-level software buffer used by
the driver. Not to be confused with <c>sndbuf</c>
and <c>recbuf</c> options which correspond to
the kernel socket buffers. It is recommended
to have <c>val(buffer) >= max(val(sndbuf),val(recbuf))</c>.
In fact, the <c>val(buffer)</c> is automatically set to
the above maximum when <c>sndbuf</c> or <c>recbuf</c> values are set.</p>
</item>
<tag><c>{delay_send, Boolean}</c></tag>
<item>
<p>Normally, when an Erlang process sends to a socket,
the driver will try to immediately send the data. If that
fails, the driver will use any means available to queue
up the message to be sent whenever the operating system
says it can handle it. Setting <c>{delay_send, true}</c>
will make <em>all</em> messages queue up. This makes
the messages actually sent onto the network be larger but
fewer. The option actually affects the scheduling of send
requests versus Erlang processes instead of changing any
real property of the socket. Needless to say it is an
implementation specific option. Default is <c>false</c>.</p>
</item>
<tag><c>{deliver, port | term}</c></tag>
<item> <p> When <c>{active, true}</c> delivers data on the forms
<c>port</c> : <c>{S, {data, [H1,..Hsz | Data]}}</c> or
<c>term</c> : <c>{tcp, S, [H1..Hsz | Data]}</c>.
</p>
</item>
<tag><c>{dontroute, Boolean}</c></tag>
<item>
<p>Enable/disable routing bypass for outgoing messages.</p>
</item>
<tag><c>{exit_on_close, Boolean}</c></tag>
<item>
<p>By default this option is set to <c>true</c>.</p>
<p>The only reason to set it to <c>false</c> is if you want
to continue sending data to the socket after a close has
been detected, for instance if the peer has used
<seealso marker="gen_tcp#shutdown/2">gen_tcp:shutdown/2</seealso>
to shutdown the write side.</p>
</item>
<tag><c>{header, Size}</c></tag>
<item>
<p>This option is only meaningful if the <c>binary</c>
option was specified when the socket was created. If
the <c>header</c> option is specified, the first
<c>Size</c> number bytes of data received from the socket
will be elements of a list, and the rest of the data will
be a binary given as the tail of the same list. If for
example <c>Size == 2</c>, the data received will match
<c>[Byte1,Byte2|Binary]</c>.</p>
</item>
<tag><c>{high_msgq_watermark, Size}</c></tag>
<item>
<p>The socket message queue will be set into a busy
state when the amount of data queued on the message
queue reaches this limit. Note that this limit only
concerns data that have not yet reached the ERTS internal
socket implementation. Default value used is 8 kB.</p>
<p>Senders of data to the socket will be suspended if
either the socket message queue is busy, or the socket
itself is busy.</p>
<p>For more information see the <c>low_msgq_watermark</c>,
<c>high_watermark</c>, and <c>low_watermark</c> options.</p>
<p>Note that distribution sockets will disable the use of
<c>high_msgq_watermark</c> and <c>low_msgq_watermark</c>,
and will instead use the
<seealso marker="erts:erlang#system_info_dist_buf_busy_limit">distribution
buffer busy limit</seealso> which is a similar feature.</p>
</item>
<tag><c>{high_watermark, Size}</c> (TCP/IP sockets)</tag>
<item>
<p>The socket will be set into a busy state when the amount
of data queued internally by the ERTS socket implementation
reaches this limit. Default value used is 8 kB.</p>
<p>Senders of data to the socket will be suspended if
either the socket message queue is busy, or the socket
itself is busy.</p>
<p>For more information see the <c>low_watermark</c>,
<c>high_msgq_watermark</c>, and <c>low_msqg_watermark</c>
options.</p>
</item>
<tag><c>{ipv6_v6only, Boolean}</c></tag>
<item>
<p>
Restricts the socket to only use IPv6, prohibiting any
IPv4 connections. This is only applicable for
IPv6 sockets (option <c>inet6</c>).
</p>
<p>
On most platforms this option has to be set on the socket
before associating it to an address. Therefore it is only
reasonable to give it when creating the socket and not
to use it when calling the function
(<seealso marker="#setopts/2">setopts/2</seealso>)
containing this description.
</p>
<p>
The behaviour of a socket with this socket option set to
<c>true</c> is becoming the only portable one. The original
idea when IPv6 was new of using IPv6 for all traffic
is now not recommended by FreeBSD (you can use
<c>{ipv6_v6only,false}</c> to override the recommended
system default value),
forbidden by OpenBSD (the supported GENERIC kernel)
and impossible on Windows (that has separate
IPv4 and IPv6 protocol stacks). Most Linux distros
still have a system default value of <c>false</c>.
This policy shift among operating systems towards
separating IPv6 from IPv4 traffic has evolved since
it gradually proved hard and complicated to get
a dual stack implementation correct and secure.
</p>
<p>
On some platforms the only allowed value for this option
is <c>true</c>, e.g. OpenBSD and Windows. Trying to set
this option to <c>false</c> when creating the socket
will in this case fail.
</p>
<p>
Setting this option on platforms where it does not exist
is ignored and getting this option with
<seealso marker="#getopts/2">getopts/2</seealso>
returns no value i.e the returned list will not contain an
<c>{ipv6_v6only,_}</c> tuple. On Windows the option acually
does not exist, but it is emulated as being a
read-only option with the value <c>true</c>.
</p>
<p>
So it boils down to that setting this option to <c>true</c>
when creating a socket will never fail except possibly
(at the time of this writing) on a platform where you
have customized the kernel to only allow <c>false</c>,
which might be doable (but weird) on e.g. OpenBSD.
</p>
<p>
If you read back the option value using
<seealso marker="#getopts/2">getopts/2</seealso>
and get no value the option does not exist in the host OS
and all bets are off regarding the behaviour of both
an IPv6 and an IPv4 socket listening on the same port
as well as for an IPv6 socket getting IPv4 traffic.
</p>
</item>
<tag><c>{keepalive, Boolean}</c>(TCP/IP sockets)</tag>
<item>
<p>Enables/disables periodic transmission on a connected
socket, when no other data is being exchanged. If
the other end does not respond, the connection is
considered broken and an error message will be sent to
the controlling process. Default disabled.</p>
<marker id="option-linger"></marker>
</item>
<tag><c>{linger, {true|false, Seconds}}</c></tag>
<item>
<p>Determines the timeout in seconds for flushing unsent data in the
<c>close/1</c> socket call. If the 1st component of the value
tuple is <c>false</c>, the 2nd one is ignored, which means that
<c>close/1</c> returns immediately not waiting
for data to be flushed. Otherwise, the 2nd component is
the flushing time-out in seconds.</p>
</item>
<tag><c>{low_msgq_watermark, Size}</c></tag>
<item>
<p>If the socket message queue is in a busy state, the
socket message queue will be set in a not busy state when
the amount of data queued in the message queue falls
below this limit. Note that this limit only concerns data
that have not yet reached the ERTS internal socket
implementation. Default value used is 4 kB.</p>
<p>Senders that have been suspended due to either a
busy message queue or a busy socket, will be resumed
when neither the socket message queue, nor the socket
are busy.</p>
<p>For more information see the <c>high_msgq_watermark</c>,
<c>high_watermark</c>, and <c>low_watermark</c> options.</p>
<p>Note that distribution sockets will disable the use of
<c>high_msgq_watermark</c> and <c>low_msgq_watermark</c>,
and will instead use the
<seealso marker="erts:erlang#system_info_dist_buf_busy_limit">distribution
buffer busy limit</seealso> which is a similar feature.</p>
</item>
<tag><c>{low_watermark, Size}</c> (TCP/IP sockets)</tag>
<item>
<p>If the socket is in a busy state, the socket will
be set in a not busy state when the amount of data
queued internally by the ERTS socket implementation
falls below this limit. Default value used is 4 kB.</p>
<p>Senders that have been suspended due to either a
busy message queue or a busy socket, will be resumed
when neither the socket message queue, nor the socket
are busy.</p>
<p>For more information see the <c>high_watermark</c>,
<c>high_msgq_watermark</c>, and <c>low_msgq_watermark</c>
options.</p>
</item>
<tag><c>{mode, Mode :: binary | list}</c></tag>
<item>
<p>Received <c>Packet</c> is delivered as defined by Mode.</p>
</item>
<tag><c>{netns, Namespace :: file:filename_all()}</c></tag>
<item>
<p>Set a network namespace for the socket. The <c>Namespace</c>
parameter is a filename defining the namespace for example
<c>"/var/run/netns/example"</c> typically created by the command
<c>ip netns add example</c>. This option must be used in a
function call that creates a socket i.e
<seealso marker="gen_tcp#connect/3">
gen_tcp:connect/3,4</seealso>,
<seealso marker="gen_tcp#listen/2">
gen_tcp:listen/2</seealso>,
<seealso marker="gen_udp#open/1">
gen_udp:open/1,2</seealso> or
<seealso marker="gen_sctp#open/0">
gen_sctp:open/0-2</seealso>.
</p>
<p>This option uses the Linux specific syscall
<c>setns()</c> such as in Linux kernel 3.0 or later
and therefore only exists when the runtime system
has been compiled for such an operating system.
</p>
<p>
The virtual machine also needs elevated privileges either
running as superuser or (for Linux) having the capability
<c>CAP_SYS_ADMIN</c> according to the documentation for setns(2).
However, during testing also <c>CAP_SYS_PTRACE</c>
and <c>CAP_DAC_READ_SEARCH</c> has proven to be necessary.
Example:<code>
setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp
</code>
Note also that the filesystem containing the virtual machine
executable (<c>beam.smp</c> in the example above) has to be local,
mounted without the <c>nosetuid</c> flag,
support extended attributes and that
the kernel has to support file capabilities.
All this runs out of the box on at least Ubuntu 12.04 LTS,
except that SCTP sockets appears to not support
network namespaces.
</p>
<p>The <c>Namespace</c> is a file name and is encoded
and decoded as discussed in
<seealso marker="file">file</seealso>
except that the emulator flag <c>+fnu</c> is ignored and
<seealso marker="#getopts/2">getopts/2</seealso>
for this option will return a binary for the filename
if the stored filename can not be decoded,
which should only happen if you set the option using a binary
that can not be decoded with the emulator's filename encoding:
<seealso marker="file#native_name_encoding/0">
file:native_name_encoding/0</seealso>.
</p>
</item>
<tag><c>list</c></tag>
<item>
<p>Received <c>Packet</c> is delivered as a list.</p>
</item>
<tag><c>binary</c></tag>
<item>
<p>Received <c>Packet</c> is delivered as a binary.</p>
</item>
<tag><c>{nodelay, Boolean}</c>(TCP/IP sockets)</tag>
<item>
<p>If <c>Boolean == true</c>, the <c>TCP_NODELAY</c> option
is turned on for the socket, which means that even small
amounts of data will be sent immediately.</p>
</item>
<tag><c>{packet, PacketType}</c>(TCP/IP sockets)</tag>
<item>
<p>Defines the type of packets to use for a socket.
The following values are valid:</p>
<taglist>
<tag><c>raw | 0</c></tag>
<item>
<p>No packaging is done.</p>
</item>
<tag><c>1 | 2 | 4</c></tag>
<item>
<p>Packets consist of a header specifying the number of
bytes in the packet, followed by that number of bytes.
The length of header can be one, two, or four bytes;
containing an unsigned integer in big-endian byte order.
Each send operation will generate the header, and the header
will be stripped off on each receive operation.</p>
<p>In current implementation the 4-byte header is limited to 2Gb.</p>
</item>
<tag><c>asn1 | cdr | sunrm | fcgi | tpkt | line</c></tag>
<item>
<p>These packet types only have effect on receiving.
When sending a packet, it is the responsibility of
the application to supply a correct header. On
receiving, however, there will be one message sent to
the controlling process for each complete packet
received, and, similarly, each call to
<c>gen_tcp:recv/2,3</c> returns one complete packet.
The header is <em>not</em> stripped off.</p>
<p>The meanings of the packet types are as follows:
<br></br>
<c>asn1</c> - ASN.1 BER,
<br></br>
<c>sunrm</c> - Sun's RPC encoding,
<br></br>
<c>cdr</c> - CORBA (GIOP 1.1),
<br></br>
<c>fcgi</c> - Fast CGI,
<br></br>
<c>tpkt</c> - TPKT format [RFC1006],
<br></br>
<c>line</c> - Line mode, a packet is a line
terminated with newline, lines longer than
the receive buffer are truncated.</p>
</item>
<tag><c>http | http_bin</c></tag>
<item>
<p>The Hypertext Transfer Protocol. The packets
are returned with the format according to <c>HttpPacket</c>
described in <seealso marker="erts:erlang#decode_packet/3">
erlang:decode_packet/3</seealso>. A socket in passive
mode will return <c>{ok, HttpPacket}</c> from <c>gen_tcp:recv</c>
while an active socket will send messages like <c>{http,
Socket, HttpPacket}</c>.</p>
</item>
<tag><c>httph | httph_bin</c></tag>
<item>
<p>These two types are often not needed as the socket will
automatically switch from <c>http</c>/<c>http_bin</c> to
<c>httph</c>/<c>httph_bin</c> internally after the first line
has been read. There might be occasions however when they are
useful, such as parsing trailers from chunked encoding.</p>
</item>
</taglist>
</item>
<tag><c>{packet_size, Integer}</c>(TCP/IP sockets)</tag>
<item>
<p>Sets the max allowed length of the packet body. If
the packet header indicates that the length of the packet
is longer than the max allowed length, the packet is
considered invalid. The same happens if the packet header
is too big for the socket receive buffer.</p>
<p>For line oriented protocols (<c>line</c>,<c>http*</c>),
option <c>packet_size</c> also guarantees that lines up to the
indicated length are accepted and not considered invalid due
to internal buffer limitations.</p>
</item>
<tag><c>{priority, Priority}</c></tag>
<item> <p>Set the protocol-defined priority for all packets to be sent
on this socket.</p>
</item>
<tag><c>{raw, Protocol, OptionNum, ValueBin}</c></tag>
<item> <p>See below.</p>
</item>
<tag><c>{read_packets, Integer}</c>(UDP sockets)</tag>
<item>
<p>Sets the max number of UDP packets to read without
intervention from the socket when data is available.
When this many packets have been read and delivered
to the destination process, new packets are not read
until a new notification of available data has arrived.
The default is 5, and if this parameter is set too
high the system can become unresponsive due to
UDP packet flooding.</p>
</item>
<tag><c>{recbuf, Size}</c></tag>
<item>
<p>Gives the size of the receive buffer to use for
the socket.</p>
</item>
<tag><c>{reuseaddr, Boolean}</c></tag>
<item>
<p>Allows or disallows local reuse of port numbers. By
default, reuse is disallowed.</p>
</item>
<tag><c>{send_timeout, Integer}</c></tag>
<item>
<p>Only allowed for connection oriented sockets.</p>
<p>Specifies a longest time to wait for a send operation to
be accepted by the underlying TCP stack. When the limit is
exceeded, the send operation will return
<c>{error,timeout}</c>. How much of a packet that actually
got sent is unknown, why the socket should be closed
whenever a timeout has occurred (see <c>send_timeout_close</c>).
Default is <c>infinity</c>.</p>
</item>
<tag><c>{send_timeout_close, Boolean}</c></tag>
<item>
<p>Only allowed for connection oriented sockets.</p>
<p>Used together with <c>send_timeout</c> to specify whether
the socket will be automatically closed when the send operation
returns <c>{error,timeout}</c>. The recommended setting is
<c>true</c> which will automatically close the socket.
Default is <c>false</c> due to backward compatibility.</p>
<marker id="option-sndbuf"></marker>
</item>
<tag><c>{sndbuf, Size}</c></tag>
<item>
<p>Gives the size of the send buffer to use for the socket.</p>
</item>
<tag><c>{priority, Integer}</c></tag>
<item>
<p>Sets the SO_PRIORITY socket level option on platforms where
this is implemented. The behaviour and allowed range varies on
different systems. The option is ignored on platforms where the
option is not implemented. Use with caution.</p>
</item>
<tag><c>{tos, Integer}</c></tag>
<item>
<p>Sets IP_TOS IP level options on platforms where this is
implemented. The behaviour and allowed range varies on different
systems. The option is ignored on platforms where the option is
not implemented. Use with caution.</p>
</item>
</taglist>
<p>In addition to the options mentioned above, <em>raw</em>
option specifications can be used. The raw options are
specified as a tuple of arity four, beginning with the tag
<c>raw</c>, followed by the protocol level, the option number
and the actual option value specified as a binary. This
corresponds to the second, third and fourth argument to the
<c>setsockopt</c> call in the C socket API. The option value
needs to be coded in the native endianess of the platform and,
if a structure is required, needs to follow the struct
alignment conventions on the specific platform.</p>
<p>Using raw socket options require detailed knowledge about
the current operating system and TCP stack.</p>
<p>As an example of the usage of raw options, consider a Linux
system where you want to set the <c>TCP_LINGER2</c> option on
the <c>IPPROTO_TCP</c> protocol level in the stack. You know
that on this particular system it defaults to 60 (seconds),
but you would like to lower it to 30 for a particular
socket. The <c>TCP_LINGER2</c> option is not explicitly
supported by inet, but you know that the protocol level
translates to the number 6, the option number to the number 8
and the value is to be given as a 32 bit integer. You can use
this line of code to set the option for the socket named
<c>Sock</c>:</p>
<code type="none"><![CDATA[
inet:setopts(Sock,[{raw,6,8,<<30:32/native>>}]),]]></code>
<p>As many options are silently discarded by the stack if they
are given out of range, it could be a good idea to check that
a raw option really got accepted. This code places the value
in the variable TcpLinger2:</p>
<code type="none"><![CDATA[
{ok,[{raw,6,8,<<TcpLinger2:32/native>>}]}=inet:getopts(Sock,[{raw,6,8,4}]),]]></code>
<p>Code such as the examples above is inherently non portable,
even different versions of the same OS on the same platform
may respond differently to this kind of option
manipulation. Use with care.</p>
<p>Note that the default options for TCP/IP sockets can be
changed with the Kernel configuration parameters mentioned in
the beginning of this document.</p>
</desc>
</func>
</funcs>
<section>
<marker id="error_codes"></marker>
<title>POSIX Error Codes</title>
<list type="bulleted">
<item><c>e2big</c> - argument list too long</item>
<item><c>eacces</c> - permission denied</item>
<item><c>eaddrinuse</c> - address already in use</item>
<item><c>eaddrnotavail</c> - cannot assign requested address</item>
<item><c>eadv</c> - advertise error</item>
<item><c>eafnosupport</c> - address family not supported by
protocol family</item>
<item><c>eagain</c> - resource temporarily unavailable</item>
<item><c>ealign</c> - EALIGN</item>
<item><c>ealready</c> - operation already in progress</item>
<item><c>ebade</c> - bad exchange descriptor</item>
<item><c>ebadf</c> - bad file number</item>
<item><c>ebadfd</c> - file descriptor in bad state</item>
<item><c>ebadmsg</c> - not a data message</item>
<item><c>ebadr</c> - bad request descriptor</item>
<item><c>ebadrpc</c> - RPC structure is bad</item>
<item><c>ebadrqc</c> - bad request code</item>
<item><c>ebadslt</c> - invalid slot</item>
<item><c>ebfont</c> - bad font file format</item>
<item><c>ebusy</c> - file busy</item>
<item><c>echild</c> - no children</item>
<item><c>echrng</c> - channel number out of range</item>
<item><c>ecomm</c> - communication error on send</item>
<item><c>econnaborted</c> - software caused connection abort</item>
<item><c>econnrefused</c> - connection refused</item>
<item><c>econnreset</c> - connection reset by peer</item>
<item><c>edeadlk</c> - resource deadlock avoided</item>
<item><c>edeadlock</c> - resource deadlock avoided</item>
<item><c>edestaddrreq</c> - destination address required</item>
<item><c>edirty</c> - mounting a dirty fs w/o force</item>
<item><c>edom</c> - math argument out of range</item>
<item><c>edotdot</c> - cross mount point</item>
<item><c>edquot</c> - disk quota exceeded</item>
<item><c>eduppkg</c> - duplicate package name</item>
<item><c>eexist</c> - file already exists</item>
<item><c>efault</c> - bad address in system call argument</item>
<item><c>efbig</c> - file too large</item>
<item><c>ehostdown</c> - host is down</item>
<item><c>ehostunreach</c> - host is unreachable</item>
<item><c>eidrm</c> - identifier removed</item>
<item><c>einit</c> - initialization error</item>
<item><c>einprogress</c> - operation now in progress</item>
<item><c>eintr</c> - interrupted system call</item>
<item><c>einval</c> - invalid argument</item>
<item><c>eio</c> - I/O error</item>
<item><c>eisconn</c> - socket is already connected</item>
<item><c>eisdir</c> - illegal operation on a directory</item>
<item><c>eisnam</c> - is a named file</item>
<item><c>el2hlt</c> - level 2 halted</item>
<item><c>el2nsync</c> - level 2 not synchronized</item>
<item><c>el3hlt</c> - level 3 halted</item>
<item><c>el3rst</c> - level 3 reset</item>
<item><c>elbin</c> - ELBIN</item>
<item><c>elibacc</c> - cannot access a needed shared library</item>
<item><c>elibbad</c> - accessing a corrupted shared library</item>
<item><c>elibexec</c> - cannot exec a shared library directly</item>
<item><c>elibmax</c> - attempting to link in more shared
libraries than system limit</item>
<item><c>elibscn</c> - .lib section in a.out corrupted</item>
<item><c>elnrng</c> - link number out of range</item>
<item><c>eloop</c> - too many levels of symbolic links</item>
<item><c>emfile</c> - too many open files</item>
<item><c>emlink</c> - too many links</item>
<item><c>emsgsize</c> - message too long</item>
<item><c>emultihop</c> - multihop attempted</item>
<item><c>enametoolong</c> - file name too long</item>
<item><c>enavail</c> - not available</item>
<item><c>enet</c> - ENET</item>
<item><c>enetdown</c> - network is down</item>
<item><c>enetreset</c> - network dropped connection on reset</item>
<item><c>enetunreach</c> - network is unreachable</item>
<item><c>enfile</c> - file table overflow</item>
<item><c>enoano</c> - anode table overflow</item>
<item><c>enobufs</c> - no buffer space available</item>
<item><c>enocsi</c> - no CSI structure available</item>
<item><c>enodata</c> - no data available</item>
<item><c>enodev</c> - no such device</item>
<item><c>enoent</c> - no such file or directory</item>
<item><c>enoexec</c> - exec format error</item>
<item><c>enolck</c> - no locks available</item>
<item><c>enolink</c> - link has be severed</item>
<item><c>enomem</c> - not enough memory</item>
<item><c>enomsg</c> - no message of desired type</item>
<item><c>enonet</c> - machine is not on the network</item>
<item><c>enopkg</c> - package not installed</item>
<item><c>enoprotoopt</c> - bad protocol option</item>
<item><c>enospc</c> - no space left on device</item>
<item><c>enosr</c> - out of stream resources or not a stream
device</item>
<item><c>enosym</c> - unresolved symbol name</item>
<item><c>enosys</c> - function not implemented</item>
<item><c>enotblk</c> - block device required</item>
<item><c>enotconn</c> - socket is not connected</item>
<item><c>enotdir</c> - not a directory</item>
<item><c>enotempty</c> - directory not empty</item>
<item><c>enotnam</c> - not a named file</item>
<item><c>enotsock</c> - socket operation on non-socket</item>
<item><c>enotsup</c> - operation not supported</item>
<item><c>enotty</c> - inappropriate device for ioctl</item>
<item><c>enotuniq</c> - name not unique on network</item>
<item><c>enxio</c> - no such device or address</item>
<item><c>eopnotsupp</c> - operation not supported on socket</item>
<item><c>eperm</c> - not owner</item>
<item><c>epfnosupport</c> - protocol family not supported</item>
<item><c>epipe</c> - broken pipe</item>
<item><c>eproclim</c> - too many processes</item>
<item><c>eprocunavail</c> - bad procedure for program</item>
<item><c>eprogmismatch</c> - program version wrong</item>
<item><c>eprogunavail</c> - RPC program not available</item>
<item><c>eproto</c> - protocol error</item>
<item><c>eprotonosupport</c> - protocol not supported</item>
<item><c>eprototype</c> - protocol wrong type for socket</item>
<item><c>erange</c> - math result unrepresentable</item>
<item><c>erefused</c> - EREFUSED</item>
<item><c>eremchg</c> - remote address changed</item>
<item><c>eremdev</c> - remote device</item>
<item><c>eremote</c> - pathname hit remote file system</item>
<item><c>eremoteio</c> - remote i/o error</item>
<item><c>eremoterelease</c> - EREMOTERELEASE</item>
<item><c>erofs</c> - read-only file system</item>
<item><c>erpcmismatch</c> - RPC version is wrong</item>
<item><c>erremote</c> - object is remote</item>
<item><c>eshutdown</c> - cannot send after socket shutdown</item>
<item><c>esocktnosupport</c> - socket type not supported</item>
<item><c>espipe</c> - invalid seek</item>
<item><c>esrch</c> - no such process</item>
<item><c>esrmnt</c> - srmount error</item>
<item><c>estale</c> - stale remote file handle</item>
<item><c>esuccess</c> - Error 0</item>
<item><c>etime</c> - timer expired</item>
<item><c>etimedout</c> - connection timed out</item>
<item><c>etoomanyrefs</c> - too many references</item>
<item><c>etxtbsy</c> - text file or pseudo-device busy</item>
<item><c>euclean</c> - structure needs cleaning</item>
<item><c>eunatch</c> - protocol driver not attached</item>
<item><c>eusers</c> - too many users</item>
<item><c>eversion</c> - version mismatch</item>
<item><c>ewouldblock</c> - operation would block</item>
<item><c>exdev</c> - cross-domain link</item>
<item><c>exfull</c> - message tables full</item>
<item><c>nxdomain</c> - the hostname or domain name could not be
found</item>
</list>
</section>
</erlref>