socket
Module
Module Summary
Since
Description
This module provides an API for network socket. Functions are provided to create, delete and manupilate the sockets aswell as sending and reciving data on them.
The intent is that it shall be as "close as possible" to the OS level socket interface. The only significant addition is that some of the functions, e.g. recv/3, has a timeout argument.
Some functions allow for an asynchronous call. This is achieved by setting the Timeout argument to nowait. For instance, if calling the recv/3 function with Timeout set to nowait (recv(Sock, 0, nowait)) when there is actually nothing to read, it will return with {select, SelectInfo} (SelectInfo contains the SelectRef). When data eventually arrives a 'select' message will be sent to the caller:
- {'$socket', socket(), select, SelectRef}
The caller can now make another call to the recv function and now expect data.
Note that all other users are locked out until the 'current user' has called the function (recv in this case).
Another message the user must be prepared for (when making asynchronous calls) is the abort message:
- {'$socket', socket(), abort, Info}
This message indicates that the (asynchronous) operation has been aborted. If, for instance, the socket has been closed (by another process), Info will be {SelectRef, closed}.
There is currently no support for Windows.
Support for IPv6 has been implemented but not tested.
SCTP has only been partly implemented (and not tested).
Data Types
As returned by open/1,2,3,4 and accept/1,2.
A tag that describes the (select) operation.
A reference that uniquely identifies the (select) operation.
read_byte | read_fails | read_pkg | read_pkg_max |
read_tries | read_waits | write_byte | write_fails |
write_pkg | write_pkg_max | write_tries | write_waits |
acc_success | acc_fails | acc_tries | acc_waits
#{domain := domain(),
type := type(),
protocol := protocol(),
ctrl := pid(),
ctype := normal | fromfd | {fromfd, integer()},
counters := socket_counters(),
num_readers := integer() >= 0,
num_writers := integer() >= 0,
num_acceptors := integer() >= 0,
writable := boolean(),
readable := boolean()}
#{family := inet,
port := port_number(),
addr := any | broadcast | loopback | ip4_address()}
#{family := inet6,
port := port_number(),
addr := any | loopback | ip6_address(),
flowinfo := in6_flow_info(),
scope_id := in6_scope_id()}
#{family := packet,
protocol := integer() >= 0,
ifindex := integer(),
pkttype := packet_type(),
hatype := integer() >= 0,
addr := binary()}
host | broadcast | multicast | otherhost | outgoing |
loopback | user | kernel | fastroute |
integer() >= 0
debug | iow | controlling_process | rcvbuf | rcvctrlbuf |
sndctrlbuf | meta | fd
acceptconn | acceptfilter | bindtodevice | broadcast |
busy_poll | debug | domain | dontroute | error | keepalive |
linger | mark | oobinline | passcred | peek_off | peercred |
priority | protocol | rcvbuf | rcvbufforce | rcvlowat |
rcvtimeo | reuseaddr | reuseport | rxq_ovfl | setfib |
sndbuf | sndbufforce | sndlowat | sndtimeo | timestamp | type
add_membership | add_source_membership | block_source |
dontfrag | drop_membership | drop_source_membership |
freebind | hdrincl | minttl | msfilter | mtu | mtu_discover |
multicast_all | multicast_if | multicast_loop |
multicast_ttl | nodefrag | options | pktinfo | recverr |
recvif | recvdstaddr | recvopts | recvorigdstaddr | recvtos |
recvttl | retopts | router_alert | sndsrcaddr | tos |
transparent | ttl | unblock_source
addrform | add_membership | authhdr | auth_level | checksum |
drop_membership | dstopts | esp_trans_level |
esp_network_level | faith | flowinfo | hopopts |
ipcomp_level | join_group | leave_group | mtu | mtu_discover |
multicast_hops | multicast_if | multicast_loop | portrange |
pktoptions | recverr | recvhoplimit | hoplimit | recvpktinfo |
pktinfo | recvtclass | router_alert | rthdr | tclass |
unicast_hops | use_min_mtu | v6only
congestion | cork | info | keepcnt | keepidle | keepintvl |
maxseg | md5sig | nodelay | noopt | nopush | syncnt |
user_timeout
adaption_layer | associnfo | auth_active_key | auth_asconf |
auth_chunk | auth_key | auth_delete_key | autoclose |
context | default_send_params | delayed_ack_time |
disable_fragments | hmac_ident | events | explicit_eor |
fragment_interleave | get_peer_addr_info | initmsg |
i_want_mapped_v4_addr | local_auth_chunks | maxseg |
maxburst | nodelay | partial_delivery_point |
peer_addr_params | peer_auth_chunks | primary_addr |
reset_streams | rtoinfo | set_peer_primary_addr | status |
use_ext_recvinfo
#{multiaddr := ip4_address(),
interface := ip4_address(),
sourceaddr := ip4_address()}
#{multiaddr := ip4_address(),
interface := ip4_address(),
mode := ip_msfilter_mode(),
slist := [ip4_address()]}
#{stream := uint16(),
ssn := uint16(),
flags := uint16(),
ppid := uint16(),
context := uint16(),
timetolive := uint16(),
tsn := uint16(),
cumtsn := uint16(),
assoc_id := sctp_assoc_id()}
#{data_in := boolean(),
association := boolean(),
address := boolean(),
send_failure := boolean(),
peer_error := boolean(),
shutdown := boolean(),
partial_delivery := boolean(),
adaptation_layer := boolean(),
authentication := boolean(),
sender_dry := boolean()}
#{assoc_id := sctp_assoc_id(),
max_rxt := uint16(),
num_peer_dests := uint16(),
peer_rwnd := uint32(),
local_rwnd := uint32(),
cookie_life := uint32()}
#{num_outstreams := uint16(),
max_instreams := uint16(),
max_attempts := uint16(),
max_init_timeo := uint16()}
#{assoc_id := sctp_assoc_id(),
initial := uint32(),
max := uint32(),
min := uint32()}
#{addr := sockaddr(),
iov := [binary()],
ctrl := [cmsghdr_recv()] | [cmsghdr_send()],
flags := msghdr_flags()}
credentials | hoplevel | origdstaddr | pktinfo | recvtos |
rights | timestamp | tos | ttl |
integer()
#{level := socket, type := timestamp, data := timeval()} |
#{level := socket, type := rights, data := binary()} |
#{level := socket, type := credentials, data := binary()} |
#{level := socket, type := integer(), data := binary()} |
#{level := ip, type := tos, data := ip_tos()} |
#{level := ip, type := recvtos, data := ip_tos()} |
#{level := ip, type := ttl, data := integer()} |
#{level := ip, type := recvttl, data := integer()} |
#{level := ip, type := pktinfo, data := ip_pktinfo()} |
#{level := ip, type := origdstaddr, data := sockaddr_in4()} |
#{level := ip,
type := recverr,
data := extended_err() | binary()} |
#{level := ip, type := integer(), data := binary()} |
#{level := ipv6, type := hoplevel, data := integer()} |
#{level := ipv6, type := pktinfo, data := ipv6_pktinfo()} |
#{level := ipv6,
type := recverr,
data := extended_err() | binary()} |
#{level := ipv6, type := tclass, data := integer()} |
#{level := ipv6, type := integer(), data := binary()} |
#{level := integer(), type := integer(), data := binary()}
#{level := socket, type := timestamp, data := binary()} |
#{level := socket, type := rights, data := binary()} |
#{level := socket, type := credentials, data := binary()} |
#{level := socket, type := integer(), data := binary()} |
#{level := ip, type := tos, data := ip_tos() | binary()} |
#{level := ip, type := ttl, data := integer() | binary()} |
#{level := ip, type := integer(), data := binary()} |
#{level := ipv6, type := tclass, data := integer()} |
#{level := ipv6, type := integer(), data := binary()} |
#{level := udp, type := integer(), data := binary()} |
#{level := integer(), type := integer(), data := binary()}
net_unreach | host_unreach | port_unreach | frag_needed |
net_unknown | host_unknown |
uint8()
noroute | adm_prohibited | not_neighbour | addr_unreach |
port_unreach | policy_fail | reject_route |
uint8()
#{error := term(),
origin := icmp,
type := dest_unreach,
code := icmp_dest_unreach(),
info := uint32(),
data := uint32(),
offender := undefined | sockaddr()} |
#{error := term(),
origin := icmp,
type := time_exceeded | uint8(),
code := uint8(),
info := uint32(),
data := uint32(),
offender := undefined | sockaddr()} |
#{error := term(),
origin := icmp6,
type := dest_unreach,
code := icmpv6_dest_unreach(),
info := uint32(),
data := uint32(),
offender := undefined | sockaddr()} |
#{error := term(),
origin := icmp6,
type := pkt_toobig | time_exceeded | uint8(),
code := uint8(),
info := uint32(),
data := uint32(),
offender := undefined | sockaddr()} |
#{error := term(),
origin := ee_origin(),
type := uint8(),
code := uint8(),
info := uint32(),
data := uint32(),
offender := undefined | sockaddr()}
[{socket, supports_options_socket()} |
{ip, supports_options_ip()} |
{ipv6, supports_options_ipv6()} |
{tcp, supports_options_tcp()} |
{udp, supports_options_udp()} |
{sctp, supports_options_sctp()}]
Exports
OTP 22.0 |
OTP 22.0 |
Accept a connection on a socket.
This call is used with connection-based socket types (stream or seqpacket). It extracs the first pending connection request for the listen socket and returns the (newly) connected socket.
OTP 22.1 |
Accept a connection on a socket.
This call is used with connection-based socket types (stream or seqpacket). It extracs the first pending connection request for the listen socket and returns the (newly) connected socket.
In the case when there is no connections waiting, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when a client connects (a subsequent call to accept will then return the socket).
OTP 22.0 |
Types
Bind a name to a socket.
When a socket is created (with open), it has no address assigned to it. bind assigns the address specified by the Addr argument.
The rules used for name binding vary between domains.
OTP 22.1 |
Cancel an asynchronous request.
Call this function in order to cancel a previous asynchronous call to, e.g. recv/3.
OTP 22.0 |
Closes the socket.
Note that for e.g. protocol = tcp, most implementations doing a close does not guarantee that any data sent is delivered to the recipient before the close is detected at the remote side.
One way to handle this is to use the shutdown function (socket:shutdown(Socket, write)) to signal that no more data is to be sent and then wait for the read side of the socket to be closed.
OTP 22.0 |
OTP 22.0 |
This function connects the socket to the address specied by the SockAddr argument.
OTP 22.1 |
This function connects the socket to the address specied by the SockAddr argument.
In the case when its not possible to immediately establish a connection, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo, a subsequent call to connect will then establish the connection).
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Get an option on a socket.
What properties are valid depend both on Level and on what kind of socket it is (domain, type and protocol).
See the socket options chapter of the users guide for more info.
Not all options are valid on all platforms. That is, even if "we" support an option, that does not mean that the underlying OS does.
OTP 22.0 |
Types
Get an option on a socket.
When specifying Level as an integer, and therefor using "native mode", it is *currently* up to the caller to know how to interpret the result.
For more info, see getopt above.
info(Socket) -> socket_info()
|
OTP 22.1 |
Types
Get miscellaneous info about the socket.
The function returns a map with each info item as a key-value binding. It reflects the "current" state of the socket.
In order to ensure data integrity, mutex'es are taken when needed. So, do not call this function often.
OTP 22.0 |
OTP 22.0 |
Listen for connections on a socket.
OTP 22.3 |
Returns the number of active sockets.
OTP 23.0 |
OTP 23.0 |
Create an endpoint (socket) for communication based on an already existing file descriptor. The function attempts to retrieve domain, type and protocol from the system. This is however not possible on all platforms, and in those cases it expects it in Opts.
The Opts argument is intended for providing extra information for the open call:
- dup: boolean()
-
Shall the provided descriptor be duplicated (dup) or not.
Defaults to true. - debug: boolean()
-
Enable or disable debug during the open call.
Defaults to false. - domain: socket:domain()
-
Which domain is the descriptor of.
- type: socket:type()
-
Which type is the descriptor of.
- protocol: socket:protocol()
-
Which protocol is the descriptor of.
This function should be used with care!
On some platforms its necessary to provide the protocol as its impossible to retrieve it.
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
Creates an endpoint (socket) for communication.
For some types there is a default protocol, indicated by default, which it may be possible to specify. And for Domain = local, if a protocol is pecified, it must be default.
The Opts argument is intended for "other" options. Currently the only supported option(s) are netns, which is only supported on the linux platform and debug (controls debug printouts during the open call).
It may not be possible to specify the default protocol (except when Domain = local). We need to be able to retreive the resulting protocol, which is not possble on all platforms.
OTP 22.0 |
Returns the address of the peer connected to the socket.
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
Receive a message from a socket.
There is a special case for the argument Length. If it is set to zero (0), it means "give me everything you currently have".
OTP 22.1 |
OTP 22.1 |
Types
Receive a message from a socket.
There is a special case for the argument Length. If it is set to zero (0), it means "give me everything you currently have".
In the case when there is no data waiting, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when data has arrived (a subsequent call to recv will then return the data).
Note that if a length (> 0) is specified, and only part of that amount of data is available, the function will return with that data and the SelectInfo (if the caller don't want to wait for the remaining data, it must immediately call the cancel/2 function.)
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
Receive a message from a socket.
This function reads "messages", which means that regardless of how much we want to read, it returns when we get a message (if the buffer size is too small, the message will be truncated).
The BufSz argument basically defines the size of the receive buffer. By setting the value to zero (0), the configured size (setopt with Level = otp and Key = rcvbuf) is used.
It may be impossible to know what (buffer) size is appropriate "in advance", and in those cases it may be convenient to use the (recv) 'peek' flag. When this flag is provided, the message is *not* "consumed" from the underlying buffers, so another recvfrom call is needed, possibly with a then adjusted buffer size.
OTP 22.1 |
OTP 22.1 |
OTP 22.1 |
Types
Receive a message from a socket.
This function reads "messages", which means that regardless of how much we want to read, it returns when we get a message (if the buffer size is too small, the message will be truncated).
The BufSz argument basically defines the size of the receive buffer. By setting the value to zero (0), the configured size (setopt with Level = otp and Key = rcvbuf) is used.
It may be impossible to know what (buffer) size is appropriate "in advance", and in those cases it may be convenient to use the (recv) 'peek' flag. When this flag is provided, the message is *not* "consumed" from the underlying buffers, so another recvfrom call is needed, possibly with a then adjusted buffer size.
In the case when there is no data waiting, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when data has arrived (a subsequent call to recvfrom will then return the data).
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
Receive a message from a socket.
This function reads "messages", which means that regardless of how much we want to read, it returns when we get a message.
The message will be delivered in the form of a msghdr(), which may contain the source address (if socket not connected), a list of cmsghdr_recv() (depends on what socket options have been set and what the protocol and platform supports) and also a set of flags, providing further info about the read.
The BufSz argument basically defines the size of the receive buffer. By setting the value to zero (0), the configured size (setopt with Level = otp and Key = rcvbuf) is used.
The CtrlSz argument basically defines the size of the receive buffer for the control messages. By setting the value to zero (0), the configured size (setopt with Level = otp) is used.
It may be impossible to know what (buffer) size is appropriate "in advance", and in those cases it may be convenient to use the (recv) 'peek' flag. When this flag is provided, the message is *not* "consumed" from the underlying buffers, so another recvmsg call is needed, possibly with a then adjusted buffer size.
OTP 22.1 |
OTP 22.1 |
OTP 22.1 |
Types
Receive a message from a socket.
This function reads "messages", which means that regardless of how much we want to read, it returns when we get a message.
The message will be delivered in the form of a msghdr(), which may contain the source address (if socket not connected), a list of cmsghdr_recv() (depends on what socket options have been set and what the protocol and platform supports) and also a set of flags, providing further info about the read.
The BufSz argument basically defines the size of the receive buffer. By setting the value to zero (0), the configured size (setopt with Level = otp and Key = rcvbuf) is used.
The CtrlSz argument basically defines the size of the receive buffer for the control messages. By setting the value to zero (0), the configured size (setopt with Level = otp) is used.
It may be impossible to know what (buffer) size is appropriate "in advance", and in those cases it may be convenient to use the (recv) 'peek' flag. When this flag is provided, the message is *not* "consumed" from the underlying buffers, so another recvmsg call is needed, possibly with a then adjusted buffer size.
In the case when there is no data waiting, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when data has arrived (a subsequent call to recvmsg will then return the data).
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Send a message on a connected socket.
OTP 22.1 |
OTP 22.1 |
Types
Send a message on a connected socket.
In the case when there is no room in the (system-) buffers, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when there is room for more data (a subsequent call to send will then send the data).
Note that if not all the data was sent, the function will return with the remaining data and the SelectInfo (if the caller don't want to wait to be able to send the rest, it should immediately call the cancel/2 function.)
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
Send a message on a socket. The destination, if needed (socket not connected) is provided in the MsgHdr, which also contains the message to send, The MsgHdr may also contain an list of optional cmsghdr_send() (depends on what the protocol and platform supports).
Unlike the send function, this one sends one message. This means that if, for whatever reason, its not possible to send the message in one go, the function will instead return with the remaining data ({ok, Remaining}). Thereby leaving it up to the caller to decide what to do (retry with the remaining data of give up).
OTP 22.1 |
OTP 22.1 |
Types
Send a message on a socket. The destination, if needed (socket not connected) is provided in the MsgHdr, which also contains the message to send, The MsgHdr may also contain an list of optional cmsghdr_send() (depends on what the protocol and platform supports).
Unlike the send function, this one sends one message. This means that if, for whatever reason, its not possible to send the message in one go, the function will instead return with the remaining data ({ok, Remaining}). Thereby leaving it up to the caller to decide what to do (retry with the remaining data of give up).
In the case when there is no room in the (system-) buffers, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when there is room for more data (a subsequent call to sendmsg will then send the data).
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
Send a message on a socket, to the specified destination.
OTP 22.1 |
OTP 22.1 |
Types
Send a message on a socket, to the specified destination.
In the case when there is no room in the (system-) buffers, the function will return with the SelectInfo. The caller can then await a select message, {'$socket', Socket, select, Info} (where Info is the ref field from the SelectInfo), when there is room for more data (a subsequent call to sendto will then send the data).
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Set options on a socket.
What properties are valid depend both on Level and on what kind of socket it is (domain, type and protocol).
See the socket options chapter of the users guide for more info.
Not all options are valid on all platforms. That is, even if "we" support an option, that does not mean that the underlying OS does.
Sockets are set 'non-blocking' when created, so this option is *not* available (as it would adversely effect the Erlang VM to set a socket 'blocking').
OTP 22.0 |
Set options on a socket.
When specifying Level as an integer, and therefor using "native mode", it is *currently* up to the caller to know how to encode the Value.
For more info, see setopt above.
OTP 22.0 |
Shut down all or part of a full-duplex connection.
OTP 22.0 |
Returns the current address to which the socket is bound.
supports() -> [{options, supports_options()} | {sctp, boolean()} | {ipv6, boolean()} | {local, boolean()} | {send_flags, supports_send_flags()} | {recv_flags, supports_recv_flags()} | {netns, boolean()}] |
OTP 22.0 |
supports(Key1 :: options) -> supports_options()
|
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
supports(Key1 :: send_flags) -> supports_send_flags()
|
OTP 22.3 |
supports(Key1 :: recv_flags) -> supports_recv_flags()
|
OTP 22.3 |
OTP 23.0 |
OTP 22.0 |
OTP 22.0 |
supports(Key1 :: options, Level :: ip) -> supports_options_ip()
|
OTP 22.0 |
OTP 22.0 |
supports(Key1 :: options, Level :: tcp) -> supports_options_tcp()
|
OTP 22.0 |
supports(Key1 :: options, Level :: udp) -> supports_options_udp()
|
OTP 22.0 |
OTP 22.0 |
supports(Key1 :: send_flags, SendFlag :: send_flag()) -> boolean() |
OTP 22.3 |
supports(Key1 :: recv_flags, RecvFlag :: recv_flag()) -> boolean() |
OTP 22.3 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
OTP 22.0 |
Types
This function intends to retreive information about what the platform supports. Such as if SCTP is supported. Or which socket options are supported.
which_sockets() -> [socket()] |
OTP 22.3 |
which_sockets(FilterRule) -> [socket()] |
OTP 22.3 |
Types
inet | inet6 | stream | dgram | seqpacket | sctp | tcp | udp |
pid() |
fun((socket_info()) -> boolean())
Returns a list of all sockets, according to the filter rule.
There are several pre-made filter rule(s) and one general:
- inet | inet6
-
Selection based on the domain of the socket.
Only a subset is valid. - stream | dgram | seqpacket
-
Selection based on the type of the socket.
Only a subset is valid. - sctp | tcp | udp
-
Selection based on the protocol of the socket.
Only a subset is valid. - pid()
-
Selection base on which sockets has this pid as Controlling Process.
- fun((socket_info()) -> boolean())
-
The general filter rule.
A fun that takes the socket info and returns a boolean() (true if the socket sould be included and false if should not).
Examples
client(Addr, SAddr, SPort) -> {ok, Sock} = socket:open(inet, stream, tcp), {ok, _} = socket:bind(Sock, #{family => inet, addr => Addr}), ok = socket:connect(Sock, #{family => inet, addr => SAddr, port => SPort}), Msg = list_to_binary("hello"), ok = socket:send(Sock, Msg), ok = socket:shutdown(Sock, write), {ok, Msg} = socket:recv(Sock), ok = socket:close(Sock). server(Addr, Port) -> {ok, LSock} = socket:open(inet, stream, tcp), {ok, _} = socket:bind(LSock, #{family => inet, port => Port, addr => Addr}), ok = socket:listen(LSock), {ok, Sock} = socket:accept(LSock), {ok, Msg} = socket:recv(Sock), ok = socket:send(Sock, Msg), ok = socket:shutdown(Sock, write), ok = socket:close(Sock), ok = socket:close(LSock).