Erlang Run-Time System Application (ERTS)

Reference Manual

Version 10.4

Table of Contents

socket

Module

socket

Module Summary

Socket interface.

Since

Module socket was introduced in OTP 22.0.

Description

This module provides an API for the socket interface. It is used to create, delete and manipulate sockets, send and receive data.

The idea 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.

Note

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

domain() = local | inet | inet6
type() = stream | dgram | raw | rdm | seqpacket
protocol() =
    ip | tcp | udp | sctp | icmp | igmp | {raw, integer()}

As returned by open/2,3,4 and accept/1,2.

ip4_address() = {0..255, 0..255, 0..255, 0..255}
ip6_address() =
    {0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535}

sockaddr_in4() =
    #{family := inet,
      port := port_number(),
      addr := any | loopback | ip4_address()}

sockaddr_in6() =
    #{family := inet6,
      port := port_number(),
      addr := any | loopback | ip6_address(),
      flowinfo := in6_flow_info(),
      scope_id := in6_scope_id()}

sockaddr_un() = #{family := local, path := binary() | string()}
port_number() = 0..65535
accept_flag() = nonblock | cloexec
send_flag() = confirm | dontroute | eor | more | nosignal | oob
recv_flag() = cmsg_cloexec | errqueue | oob | peek | trunc
shutdown_how() = read | write | read_write
sockopt_level() =
    otp | socket | ip | ipv6 | tcp | udp | sctp |
    integer() >= 0

otp_socket_option() =
    debug | iow | controlling_process | rcvbuf | rcvctrlbuf |
    sndctrlbuf | fd

socket_option() =
    acceptconn | acceptfilter | bindtodevice | broadcast |
    busy_poll | debug | domain | dontroute | error | keepalive |
    linger | mark | oobinline | passcred | peek_off | peekcred |
    priority | protocol | rcvbuf | rcvbufforce | rcvlowat |
    rcvtimeo | reuseaddr | reuseport | rxq_ovfl | setfib |
    sndbuf | sndbufforce | sndlowat | sndtimeo | timestamp | type

ip_socket_option() =
    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

ipv6_socket_option() =
    addrform | add_membership | authhdr | auth_level | checksum |
    drop_membership | dstopts | esp_trans_level |
    esp_network_level | faith | flowinfo | hoplimit | hopopts |
    ipcomp_level | join_group | leave_group | mtu | mtu_discover |
    multicast_hops | multicast_if | multicast_loop | portrange |
    pktoptions | recverr | recvpktinfo | pktinfo | recvtclass |
    router_alert | rthdr | tclass | unicast_hops | use_min_mtu |
    v6only

tcp_socket_option() =
    congestion | cork | info | keepcnt | keepidle | keepintvl |
    maxseg | md5sig | nodelay | noopt | nopush | syncnt |
    user_timeout

sctp_socket_option() =
    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

timeval() = #{sec := integer(), usec := integer()}
ip_tos() =
    lowdeley | throughput | reliability | mincost | integer()

ip_mreq() =
    #{multiaddr := ip4_address(),
      interface := any | ip4_address()}

ip_mreq_source() =
    #{multiaddr := ip4_address(),
      interface := ip4_address(),
      sourceaddr := ip4_address()}

ip_pmtudisc() = want | dont | do | probe
ip_msfilter_mode() = include | exclude
ip_msfilter() =
    #{multiaddr := ip4_address(),
      interface := ip4_address(),
      mode := ip_msfilter_mode(),
      slist := [ip4_address()]}

ip_pktinfo() =
    #{ifindex := integer() >= 0,
      spec_dst := ip4_address(),
      addr := ip4_address()}

ipv6_mreq() =
    #{multiaddr := ip6_address(), interface := integer() >= 0}

ipv6_pktinfo() = #{addr := ip6_address(), ifindex := integer()}
sctp_sndrcvinfo() =
    #{stream := uint16(),
      ssn := uint16(),
      flags := uint16(),
      ppid := uint16(),
      context := uint16(),
      timetolive := uint16(),
      tsn := uint16(),
      cumtsn := uint16(),
      assoc_id := sctp_assoc_id()}

sctp_event_subscribe() =
    #{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()}

sctp_assocparams() =
    #{assoc_id := sctp_assoc_id(),
      max_rxt := uint16(),
      num_peer_dests := uint16(),
      peer_rwnd := uint32(),
      local_rwnd := uint32(),
      cookie_life := uint32()}

sctp_initmsg() =
    #{num_outstreams := uint16(),
      max_instreams := uint16(),
      max_attempts := uint16(),
      max_init_timeo := uint16()}

sctp_rtoinfo() =
    #{assoc_id := sctp_assoc_id(),
      initial := uint32(),
      max := uint32(),
      min := uint32()}

msghdr_flag() = ctrunc | eor | errqueue | oob | trunc
msghdr() =
    #{addr := sockaddr(),
      iov := [binary()],
      ctrl := [cmsghdr_recv()] | [cmsghdr_send()],
      flags := msghdr_flags()}

cmsghdr_level() = socket | ip | ipv6 | integer()
cmsghdr_type() =
    timestamp | pktinfo | tos | ttl | rights | credentials |
    origdstaddr |
    integer()

cmsghdr_recv() =
    #{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 := ttl, data := integer()} |
    #{level := ip, type := pktinfo, data := ip_pktinfo()} |
    #{level := ip, type := origdstaddr, data := sockaddr_in4()} |
    #{level := ip, type := integer(), data := binary()} |
    #{level := ipv6, type := pktinfo, data := ipv6_pktinfo()} |
    #{level := ipv6, type := integer(), data := binary()} |
    #{level := integer(), type := integer(), data := binary()}

cmsghdr_send() =
    #{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 := integer(), data := binary()} |
    #{level := udp, type := integer(), data := binary()} |
    #{level := integer(), type := integer(), data := binary()}

uint8() = 0..255
uint16() = 0..65535
uint20() = 0..1048575
uint32() = 0..4294967295
int32() = -2147483648..2147483647
supports_options() =
    [{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

accept(LSocket) -> {ok, Socket} | {error, Reason}
OTP 22.0
accept(LSocket, Timeout) -> {ok, Socket} | {error, Reason}
OTP 22.0

Types

LSocket = socket()
Timeout = timeout()
Socket = socket()
Reason = term()

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.

bind(Socket, Addr) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Addr = any | loopback | sockaddr()
Reason = term()

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.

close(Socket) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Reason = term()

Closes the socket.

Note

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.

connect(Socket, SockAddr) -> ok | {error, Reason}
OTP 22.0
connect(Socket, SockAddr, Timeout) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
SockAddr = sockaddr()
Timeout = timeout()
Reason = term()

This function connects the socket to the address specied by the SockAddr argument.

getopt(Socket, Level :: otp, Key :: otp_socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0
getopt(Socket, Level :: socket, Key :: socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0
getopt(Socket, Level :: ip, Key :: ip_socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0
getopt(Socket, Level :: ipv6, Key :: ipv6_socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0
getopt(Socket, Level :: tcp, Key :: tcp_socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0
getopt(Socket, Level :: udp, Key :: udp_socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0
getopt(Socket, Level :: sctp, Key :: sctp_socket_option()) ->
          {ok, Value} | {error, Reason}
OTP 22.0

Types

Socket = socket()
Value = Reason = term()

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.

Note

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.

getopt(Socket, Level, Key) -> ok | {ok, Value} | {error, Reason}
OTP 22.0

Types

Socket = socket()
Level = integer()
Key = {NativeOpt, ValueSize}
NativeOpt = integer()
ValueSize = int | bool | integer() >= 0
Value = Reason = term()

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).

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.

See the socket options chapter of the users guide for more info.

Note

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.

listen(Socket) -> ok | {error, Reason}
OTP 22.0
listen(Socket, Backlog) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Backlog = integer() >= 1
Reason = term()

Listen for connections on a socket.

open(Domain, Type) -> {ok, Socket} | {error, Reason}
OTP 22.0
open(Domain, Type, Protocol) -> {ok, Socket} | {error, Reason}
OTP 22.0
open(Domain, Type, Protocol, Extra) ->
        {ok, Socket} | {error, Reason}
OTP 22.0

Types

Domain = domain()
Type = type()
Protocol = null | protocol()
Extra = map()
Socket = socket()
Reason = term()

Creates an endpoint (socket) for communication.

For some types there is a default protocol, which will be used if no protocol is specified:

  • stream: tcp

  • dgram: udp

  • seqpacket: sctp

The Extra argument is intended for "obscure" options. Currently the only supported option is netns, which is only supported on the linux platform.

peername(Socket) -> {ok, SockAddr} | {error, Reason}
OTP 22.0

Types

Socket = socket()
SockAddr = sockaddr()
Reason = term()

Returns the address of the peer connected to the socket.

recv(Socket) -> {ok, Data} | {error, Reason}
OTP 22.0
recv(Socket, Length) -> {ok, Data} | {error, Reason}
OTP 22.0
recv(Socket, Length, Flags) -> {ok, Data} | {error, Reason}
OTP 22.0
recv(Socket, Length, Timeout) -> {ok, Data} | {error, Reason}
OTP 22.0
recv(Socket, Length, Flags, Timeout) ->
        {ok, Data} | {error, Reason}
OTP 22.0

Types

Socket = socket()
Length = integer() >= 0
Flags = recv_flags()
Timeout = timeout()
Data = binary()
Reason = term()

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".

recvfrom(Socket) -> {ok, {Source, Data}} | {error, Reason}
OTP 22.0
recvfrom(Socket, BufSz) -> {ok, {Source, Data}} | {error, Reason}
OTP 22.0
recvfrom(Socket, Flags, Timeout) ->
            {ok, {Source, Data}} | {error, Reason}
OTP 22.0
recvfrom(Socket, BufSz, Flags) ->
            {ok, {Source, Data}} | {error, Reason}
OTP 22.0
recvfrom(Socket, BufSz, Timeout) ->
            {ok, {Source, Data}} | {error, Reason}
OTP 22.0
recvfrom(Socket, BufSz, Flags, Timeout) ->
            {ok, {Source, Data}} | {error, Reason}
OTP 22.0

Types

Socket = socket()
BufSz = integer() >= 0
Flags = recv_flags()
Timeout = timeout()
Source = sockaddr() | undefined
Data = binary()
Reason = term()

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 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.

recvmsg(Socket) -> {ok, MsgHdr} | {error, Reason}
OTP 22.0
recvmsg(Socket, Flags) -> {ok, MsgHdr} | {error, Reason}
OTP 22.0
recvmsg(Socket, Timeout) -> {ok, MsgHdr} | {error, Reason}
OTP 22.0
recvmsg(Socket, Flags, Timeout) -> {ok, MsgHdr} | {error, Reason}
OTP 22.0
recvmsg(Socket, BufSz, CtrlSz) -> {ok, MsgHdr} | {error, Reason}
OTP 22.0
recvmsg(Socket, BufSz, CtrlSz, Flags, Timeout) ->
           {ok, MsgHdr} | {error, Reason}
OTP 22.0

Types

Socket = socket()
BufSz = CtrlSz = integer() >= 0
Flags = recv_flags()
Timeout = timeout()
MsgHdr = msghdr()
Reason = term()

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.

send(Socket, Data) -> ok | {error, Reason}
OTP 22.0
send(Socket, Data, Flags) -> ok | {error, Reason}
OTP 22.0
send(Socket, Data, Timeout) -> ok | {error, Reason}
OTP 22.0
send(Socket, Data, Flags, Timeout) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Data = iodata()
Flags = send_flags()
Timeout = timeout()
Reason = term()

Send a message on a connected socket.

sendmsg(Socket, MsgHdr) -> ok | {error, Reason}
OTP 22.0
sendmsg(Socket, MsgHdr, Flags) -> ok | {error, Reason}
OTP 22.0
sendmsg(Socket, MsgHdr, Timeout) -> ok | {error, Reason}
OTP 22.0
sendmsg(Socket, MsgHdr, Flags, Timeout) ->
           ok | {ok, Remaining} | {error, Reason}
OTP 22.0

Types

Socket = socket()
MsgHdr = msghdr()
Flags = send_flags()
Timeout = timeout()
Remaining = erlang:iovec()
Reason = term()

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).

sendto(Socket, Data, Dest) -> ok | {error, Reason}
OTP 22.0
sendto(Socket, Data, Dest, Flags) -> ok | {error, Reason}
OTP 22.0
sendto(Socket, Data, Dest, Timeout) -> ok | {error, Reason}
OTP 22.0
sendto(Socket, Data, Dest, Flags, Timeout) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Data = binary()
Dest = null | sockaddr()
Flags = send_flags()
Timeout = timeout()
Reason = term()

Send a message on a socket, to the specified destination.

setopt(Socket, Level :: otp, Key :: otp_socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0
setopt(Socket, Level :: socket, Key :: socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0
setopt(Socket, Level :: ip, Key :: ip_socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0
setopt(Socket, Level :: ipv6, Key :: ipv6_socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0
setopt(Socket, Level :: tcp, Key :: tcp_socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0
setopt(Socket, Level :: udp, Key :: udp_socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0
setopt(Socket, Level :: sctp, Key :: sctp_socket_option(), Value) ->
          ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Value = Reason = term()

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.

Note

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.

Note

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').

setopt(Socket, Level, Key, Value) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Level = Key = integer() >= 0
Value = binary()
Reason = term()

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.

Note

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.

Note

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').

shutdown(Socket, How) -> ok | {error, Reason}
OTP 22.0

Types

Socket = socket()
Reason = term()

Shut down all or part of a full-duplex connection.

sockname(Socket) -> {ok, SockAddr} | {error, Reason}
OTP 22.0

Types

Socket = socket()
SockAddr = sockaddr()
Reason = term()

Returns the current address to which the socket is bound.

supports() ->
            [{options, supports_options()} |
             {sctp, boolean()} |
             {ipv6, boolean()}]
OTP 22.0
supports(Key1 :: options) -> supports_options()
OTP 22.0
supports(Key1 :: sctp) -> boolean()
OTP 22.0
supports(Key1 :: ipv6) -> boolean()
OTP 22.0
supports(Key1) -> false
OTP 22.0
supports(Key1 :: options, Level :: socket) ->
            supports_options_socket()
OTP 22.0
supports(Key1 :: options, Level :: ip) -> supports_options_ip()
OTP 22.0
supports(Key1 :: options, Level :: ipv6) ->
            supports_options_ipv6()
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
supports(Key1 :: options, Level :: sctp) ->
            supports_options_sctp()
OTP 22.0
supports(Key1, Key2) -> false
OTP 22.0
supports(Key1 :: options, Level :: socket, Opt) -> boolean()
OTP 22.0
supports(Key1 :: options, Level :: ip, Opt) -> boolean()
OTP 22.0
supports(Key1 :: options, Level :: ipv6, Opt) -> boolean()
OTP 22.0
supports(Key1 :: options, Level :: tcp, Opt) -> boolean()
OTP 22.0
supports(Key1 :: options, Level :: udp, Opt) -> boolean()
OTP 22.0
supports(Key1 :: options, Level :: sctp, Opt) -> boolean()
OTP 22.0
supports(Key1, Key2, Key3) -> false
OTP 22.0

Types

Key1 = Key2 = Key3 = term()

This function intends to retreive information about what the platform supports. Such as if SCTP is supported. Or which socket options are supported.

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).