![]() |
![]()
| ![]() |
![]()
NAMEinet - Access to TCP/IP protocols.DESCRIPTIONThis module provides access to TCP/IP protocols. See also ERTS User's Guide: Inet Configuration for more information about how to configure an Erlang runtime system for IP communication. The following two Kernel configuration parameters affect the behavior of all sockets opened on an Erlang node:
$ erl -sname test -kernel \ inet_default_connect_options '[{delay_send,true}]' \ inet_default_listen_options '[{delay_send,true}]'Notice that default option {active, true} cannot be changed, for internal reasons. Addresses as inputs to functions can be either a string or a tuple. For example, the IP address 150.236.20.73 can be passed to gethostbyaddr/1, either as string "150.236.20.73" or as tuple {150, 236, 20, 73}. IPv4 address examples: Address ip_address() ------- ------------ 127.0.0.1 {127,0,0,1} 192.168.42.2 {192,168,42,2}IPv6 address examples: 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}Function parse_address/1 can be useful: 1> inet:parse_address("192.168.42.2"). {ok,{192,168,42,2}} 2> inet:parse_address("FFFF::192.168.42.2"). {ok,{65535,0,0,0,0,0,49320,10754}} DATA TYPEShostent() =
The record is defined in the Kernel include file "inet.hrl".
Add the following directive to the module:
-include_lib("kernel/include/inet.hrl"). hostname() = atom() | string()
This address family only works on Unix-like systems.
File is normally a file pathname in a local filesystem. It is limited in
length by the operating system, traditionally to 108 bytes.
A binary() is passed as is to the operating system, but a string()
is encoded according to the system filename encoding mode.
Other addresses are possible, for example Linux implements "Abstract
Addresses". See the documentation for Unix Domain Sockets on your system,
normally unix in manual section 7.
In most API functions where you can use this address family the port number must
be 0.
socket_address() =
Addresses besides ip_address() ones that are returned from socket
API functions. See in particular local_address(). The
unspec family corresponds to AF_UNSPEC and can occur if the other side
has no socket address. The undefined family can only occur in the
unlikely event of an address family that the VM does not recognize.
posix() = exbadport | exbadseq | file:posix()
An atom that is named from the POSIX error codes used in Unix, and in the
runtime libraries of most C compilers. See section POSIX Error
Codes.
socket()
See gen_tcp:type-socket and
gen_udp:type-socket.
address_family() = inet | inet6 | local EXPORTSclose(Socket) -> ok
Types:
Socket = socket()
Closes a socket of any type.
format_error(Reason) -> string()
Types:
Reason = posix() | system_limit
Returns a diagnostic error string. For possible POSIX values and corresponding
strings, see section POSIX Error Codes.
get_rc() -> [{Par :: any(), Val :: any()}]
Returns the state of the Inet configuration database in form of a list of
recorded configuration parameters. For more information, see ERTS User's
Guide: Inet Configuration. Only parameters with other than default values
are returned.
getaddr(Host, Family) -> {ok, Address} | {error, posix()}
Types:
Host = ip_address() | hostname()
Returns the IP address for Host as a tuple of integers. Host can
be an IP address, a single hostname, or a fully qualified hostname.
getaddrs(Host, Family) -> {ok, Addresses} | {error, posix()}
Types:
Host = ip_address() | hostname()
Returns a list of all IP addresses for Host. Host can be an IP
address, a single hostname, or a fully qualified hostname.
gethostbyaddr(Address) -> {ok, Hostent} | {error, posix()}
Types:
Address = string() | ip_address()
Returns a hostent record for the host with the specified address.
gethostbyname(Hostname) -> {ok, Hostent} | {error, posix()}
Types:
Hostname = hostname()
Returns a hostent record for the host with the specified hostname.
If resolver option inet6 is true, an IPv6 address is looked up. If
that fails, the IPv4 address is looked up and returned on IPv6-mapped IPv4
format.
gethostbyname(Hostname, Family) -> {ok, Hostent} | {error, posix()}
Types:
Hostname = hostname()
Returns a hostent record for the host with the specified name, restricted
to the specified address family.
gethostname() -> {ok, Hostname}
Types:
Hostname = string()
Returns the local hostname. Never fails.
getifaddrs() -> {ok, Iflist} | {error, posix()}
Types:
Iflist = [{Ifname, [Ifopt]}]
{flags, [Flag]} | {addr, Addr} | {netmask, Netmask} | {broadaddr, Broadaddr} | {dstaddr, Dstaddr} | {hwaddr, Hwaddr} up | broadcast | loopback | pointtopoint | running | multicast
Returns a list of 2-tuples containing interface names and the interface
addresses. Ifname is a Unicode string. Hwaddr is hardware
dependent, for example, on Ethernet interfaces it is the 6-byte Ethernet
address (MAC address (EUI-48 address)).
The tuples {addr,Addr}, {netmask,_}, and {broadaddr,_} are
repeated in the result list if the interface has multiple addresses. If you
come across an interface with multiple {flag,_} or {hwaddr,_}
tuples, you have a strange interface or possibly a bug in this function. The
tuple {flag,_} is mandatory, all others are optional.
Do not rely too much on the order of Flag atoms or Ifopt tuples.
There are however some rules:
Warning:
On Windows, the data is fetched from different OS API functions, so the
Netmask and Broadaddr values can be calculated, just as some
Flag values. Report flagrant bugs.
getopts(Socket, Options) -> {ok, OptionValues} | {error, posix()}
Types:
Socket = socket()
Gets one or more options for a socket. For a list of available options, see
setopts/2.
The number of elements in the returned OptionValues list does not
necessarily correspond to the number of options asked for. If the operating
system fails to support an option, it is left out in the returned list. An
error tuple is returned only when getting options for the socket is impossible
(that is, the socket is closed or the buffer size in a raw request is too
large). This behavior is kept for backward compatibility reasons.
A raw option request RawOptReq = {raw, Protocol, OptionNum, ValueSpec}
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.
RawOptReq consists of tag raw 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 is to be used when the
underlying getsockopt requires input in the argument field. In
this case, the binary size is to correspond to the required buffer size of the
return value. The supplied values in a RawOptReq correspond to the
second, third, and fourth/fifth parameters to the getsockopt call in
the C socket API. The value stored in the buffer is returned as a binary
ValueBin, where all values are coded in the native endianess.
Asking for and inspecting raw socket options require low-level information about
the current operating system and TCP stack.
Example:
Consider a Linux machine where option TCP_INFO can be used to collect TCP
statistics for a socket. Assume you are interested in field tcpi_sacked
of struct tcp_info filled in when asking for TCP_INFO. To be
able to access this information, you need to know the following:
get_tcpi_sacked(Sock) -> {ok,[{raw,_,_,Info}]} = inet:getopts(Sock,[{raw,6,11,92}]), <<_:28/binary,TcpiSacked:32/native,_/binary>> = Info, TcpiSacked.Preferably, you would check the machine type, the operating system, and the Kernel version before executing anything similar to this code. getstat(Socket) -> {ok, OptionValues} | {error, posix()} getstat(Socket, Options) -> {ok, OptionValues} | {error, posix()}
Types:
Socket = socket()
stat_option() =
Gets one or more statistic options for a socket.
getstat(Socket) is equivalent to getstat(Socket, [recv_avg, recv_cnt,
recv_dvi, recv_max, recv_oct, send_avg, send_cnt, send_dvi, send_max,
send_oct]).
The following options are available:
ntoa(IpAddress) -> Address | {error, einval}
Types:
Address = string()
Parses an ip_address() and returns an IPv4 or IPv6 address
string.
parse_address(Address) -> {ok, IPAddress} | {error, einval}
Types:
Address = string()
Parses an IPv4 or IPv6 address string and returns an ip4_address()
or ip6_address(). Accepts a shortened IPv4 address string.
parse_ipv4_address(Address) -> {ok, IPv4Address} | {error, einval}
Types:
Address = string()
Parses an IPv4 address string and returns an ip4_address().
Accepts a shortened IPv4 address string.
parse_ipv4strict_address(Address) -> {ok, IPv4Address} | {error, einval}
Types:
Address = string()
Parses an IPv4 address string containing four fields, that is, not
shortened, and returns an ip4_address().
parse_ipv6_address(Address) -> {ok, IPv6Address} | {error, einval}
Types:
Address = string()
Parses an IPv6 address string and returns an ip6_address(). If an
IPv4 address string is specified, an IPv4-mapped IPv6 address is
returned.
parse_ipv6strict_address(Address) -> {ok, IPv6Address} | {error, einval}
Types:
Address = string()
Parses an IPv6 address string and returns an ip6_address(). Does
not accept IPv4 addresses.
parse_strict_address(Address) -> {ok, IPAddress} | {error, einval}
Types:
Address = string()
Parses an IPv4 or IPv6 address string and returns an ip4_address()
or ip6_address(). Does not accept a shortened IPv4
address string.
peername(Socket :: socket()) -> {ok, {ip_address(), port_number()} | returned_non_ip_address()} | {error, posix()}
Returns the address and port for the other end of a connection.
Notice that for SCTP sockets, this function returns only one of the peer
addresses of the socket. Function peernames/1,2 returns
all.
peernames(Socket :: socket()) -> {ok, [{ip_address(), port_number()} | returned_non_ip_address()]} | {error, posix()}
Equivalent to peernames(Socket, 0).
Notice that the behavior of this function for an SCTP one-to-many style socket
is not defined by the SCTP Sockets API Extensions.
peernames(Socket, Assoc) -> {ok, [{Address, Port}]} | {error, posix()}
Types:
Socket = socket()
Returns a list of all address/port number pairs for the other end of an
association Assoc of a socket.
This function can return multiple addresses for multihomed sockets, such as SCTP
sockets. For other sockets it returns a one-element list.
Notice that parameter Assoc is by the SCTP Sockets API Extensions defined
to be ignored for one-to-one style sockets. What the special value 0
means, hence its behavior for one-to-many style sockets, is unfortunately
undefined.
port(Socket) -> {ok, Port} | {error, any()}
Types:
Socket = socket()
Returns the local port number for a socket.
setopts(Socket, Options) -> ok | {error, posix()}
Types:
Socket = socket()
Sets one or more options for a socket.
The following options are available:
If the value is false (passive mode), the process must explicitly receive
incoming data by calling gen_tcp:recv/2,3,
gen_udp:recv/2,3, or gen_sctp:recv/1,2 (depending
on the type of socket).
If the value is once ({active, once}), one data message
from the socket is sent to the process. To receive one more message,
setopts/2 must be called again with option {active, once}.
If the value is an integer N 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 because of 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 setopts/2 must be called again to set the socket
back into an active mode.
When using {active, once} or {active, N}, the socket changes
behavior automatically when data is received. This can be confusing in
combination with connection-oriented sockets (that is, gen_tcp), as a
socket with {active, false} behavior reports closing differently than a
socket with {active, true} behavior. To simplify programming, a socket
where the peer closed, and this is detected while in {active, false}
mode, still generates message {tcp_closed,Socket} when set to
{active, once}, {active, true}, or {active, N} mode. It
is therefore safe to assume that message {tcp_closed,Socket}, possibly
followed by socket port termination (depending on option exit_on_close)
eventually appears when a socket changes back and forth between {active,
true} and {active, false} mode. However, when peer closing
is detected it is all up to the underlying TCP/IP stack and protocol.
Notice that {active, true} mode provides no flow control; a fast sender
can easily overflow the receiver with incoming messages. The same is true for
{active, N} mode, while the message count is greater than zero.
Use active mode only if your high-level protocol provides its own flow control
(for example, acknowledging received messages) or the amount of data exchanged
is small. {active, false} mode, use of the {active, once} mode,
or {active, N} mode with values of N appropriate for the
application provides flow control. The other side cannot send faster than the
receiver can read.
The only reason to set it to false is if you want to continue sending
data to the socket after a close is detected, for example, if the peer uses
gen_tcp:shutdown/2 to shut down the write side.
Senders of data to the socket are suspended if either the socket message queue
is busy or the socket itself is busy.
For more information, see options low_msgq_watermark,
high_watermark, and low_watermark.
Notice that distribution sockets disable the use of high_msgq_watermark
and low_msgq_watermark. Instead use the distribution buffer busy
limit, which is a similar feature.
Senders of data to the socket are suspended if either the socket message queue
is busy or the socket itself is busy.
For more information, see options low_watermark,
high_msgq_watermark, and low_msqg_watermark.
On most platforms this option must be set on the socket before associating it to
an address. It is therefore only reasonable to specify it when creating the
socket and not to use it when calling function ( setopts/2)
containing this description.
The behavior of a socket with this option set to true is 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
{ipv6_v6only,false} to override the recommended system default value),
forbidden by OpenBSD (the supported GENERIC kernel), and impossible on Windows
(which has separate IPv4 and IPv6 protocol stacks). Most Linux distros still
have a system default value of false. This policy shift among operating
systems to separate IPv6 from IPv4 traffic has evolved, as it gradually proved
hard and complicated to get a dual stack implementation correct and
secure.
On some platforms, the only allowed value for this option is true, for
example, OpenBSD and Windows. Trying to set this option to false, when
creating the socket, fails in this case.
Setting this option on platforms where it does not exist is ignored. Getting
this option with getopts/2 returns no value, that is, the
returned list does not contain an {ipv6_v6only,_} tuple. On Windows,
the option does not exist, but it is emulated as a read-only option with value
true.
Therefore, setting this option to true when creating a socket never
fails, except possibly on a platform where you have customized the kernel to
only allow false, which can be doable (but awkward) on, for example,
OpenBSD.
If you read back the option value using getopts/2 and get no
value, the option does not exist in the host operating system. The behavior of
both an IPv6 and an IPv4 socket listening on the same port, and for an IPv6
socket getting IPv4 traffic is then no longer predictable.
Senders that are suspended because of either a busy message queue or a busy
socket are resumed when the socket message queue and the socket are not
busy.
For more information, see options high_msgq_watermark,
high_watermark, and low_watermark.
Notice that distribution sockets disable the use of high_msgq_watermark
and low_msgq_watermark. Instead they use the distribution buffer
busy limit, which is a similar feature.
Senders that are suspended because of a busy message queue or a busy socket are
resumed when the socket message queue and the socket are not busy.
For more information, see options high_watermark,
high_msgq_watermark, and low_msgq_watermark.
This option uses the Linux-specific syscall setns(), such as in Linux
kernel 3.0 or later, and therefore only exists when the runtime system is
compiled for such an operating system.
The virtual machine also needs elevated privileges, either running as superuser
or (for Linux) having capability CAP_SYS_ADMIN according to the
documentation for setns(2). However, during testing also
CAP_SYS_PTRACE and CAP_DAC_READ_SEARCH have proven to be
necessary.
Example:
setcap cap_sys_admin,cap_sys_ptrace,cap_dac_read_search+epi beam.smp
Notice that the filesystem containing the virtual machine executable (
beam.smp in the example) must be local, mounted without flag
nosetuid, support extended attributes, and the kernel must support file
capabilities. All this runs out of the box on at least Ubuntu 12.04 LTS,
except that SCTP sockets appear to not support network namespaces.
Namespace is a filename and is encoded and decoded as discussed in module
file, with the following exceptions:
The 4-byte header is limited to 2Gb.
The meanings of the packet types are as follows:
For line-oriented protocols ( line, http*), option
packet_size also guarantees that lines up to the indicated length are
accepted and not considered invalid because of internal buffer
limitations.
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 returns
{error,timeout}. How much of a packet that got sent is unknown; the
socket is therefore to be closed whenever a time-out has occurred (see
send_timeout_close below). Defaults to infinity.
Used together with send_timeout to specify whether the socket is to be
automatically closed when the send operation returns {error,timeout}.
The recommended setting is true, which automatically closes the socket.
Defaults to false because of backward compatibility.
Setting this option to true allows you to distinguish between a
connection that was closed normally, and one that was aborted (intentionally
or unintentionally) by the TCP peer. A call to gen_tcp:recv/2
returns {error, econnreset}. In active mode, the controlling process
receives a {tcp_error, Socket, econnreset} message before the usual
{tcp_closed, Socket}, as is the case for any other socket error. Calls
to gen_tcp:send/2 also returns {error, econnreset} when
it is detected that a TCP peer has sent an RST.
A connected socket returned from gen_tcp:accept/1 inherits the
show_econnreset setting from the listening socket.
inet:setopts(Sock,[{raw,6,8,<<30:32/native>>}]),As many options are silently discarded by the stack if they are specified out of range; it can be a good idea to check that a raw option is accepted. The following code places the value in variable TcpLinger2: {ok,[{raw,6,8,<<TcpLinger2:32/native>>}]}=inet:getopts(Sock,[{raw,6,8,4}]),Code such as these examples is inherently non-portable, even different versions of the same OS on the same platform can respond differently to this kind of option manipulation. Use with care. Notice that the default options for TCP/IP sockets can be changed with the Kernel configuration parameters mentioned in the beginning of this manual page. sockname(Socket :: socket()) -> {ok, {ip_address(), port_number()} | returned_non_ip_address()} | {error, posix()}
Returns the local address and port number for a socket.
Notice that for SCTP sockets this function returns only one of the socket
addresses. Function socknames/1,2 returns all.
socknames(Socket :: socket()) -> {ok, [{ip_address(), port_number()} | returned_non_ip_address()]} | {error, posix()}
Equivalent to socknames(Socket, 0).
socknames(Socket, Assoc) -> {ok, [{Address, Port}]} | {error, posix()}
Types:
Socket = socket()
Returns a list of all local address/port number pairs for a socket for the
specified association Assoc.
This function can return multiple addresses for multihomed sockets, such as SCTP
sockets. For other sockets it returns a one-element list.
Notice that parameter Assoc is by the SCTP Sockets API Extensions defined
to be ignored for one-to-one style sockets. For one-to-many style sockets, the
special value 0 is defined to mean that the returned addresses must be
without any particular association. How different SCTP implementations
interprets this varies somewhat.
POSIX ERROR CODES
|