Kernel

Reference Manual

Version 7.0

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 network socket. Functions are provided to create, delete and manipulate the sockets as well as sending and receiving 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, have a timeout argument.

Note

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 SelectHandle). When data eventually arrives a 'select' message will be sent to the caller:

{'$socket', socket(), select, SelectHandle}

The caller can now make new call to the recv function and expect data.

Note that all other users are locked out until the 'current user' has called the function (recv in this case).

Instead of Timeout = nowait it is equivalent to create a SelectHandle) with make_ref() and give as Timeout. This will then be the SelectHandle in the 'select' message, which enables a compiler optimization for receiving a message containing a newly created reference() (ignore the part of the message queue that had arrived before the the reference() was created).

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 {SelectHandle, closed}.

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

A lowercase atom() representing a protocol domain on the platform named AF_* (or PF_*).

type() = stream | dgram | raw | rdm | seqpacket

A lowercase atom() representing a protocol type on the platform named SOCK_*.

protocol() = atom()

An atom() means any protocol as enumerated by the C library call getprotoent() on the platform, or at least the supported ones of ip | ipv6 | tcp | udp | sctp, and default which is equivalent to the integer protocol number 0.

See open/2,3,4

The call supports(protocols) returns the supported protocol atoms. (except for default)

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

A tag that describes the (select) operation.

select_handle() = reference()

A reference() that uniquely identifies the (select) operation.

select_info() =
    {select_info,
     SelectTag :: select_tag(),
     SelectHandle :: select_handle()}

socket_counters() =
    #{read_byte := integer() >= 0,
      read_fails := integer() >= 0,
      read_pkg := integer() >= 0,
      read_pkg_max := integer() >= 0,
      read_tries := integer() >= 0,
      read_waits := integer() >= 0,
      write_byte := integer() >= 0,
      write_fails := integer() >= 0,
      write_pkg := integer() >= 0,
      write_pkg_max := integer() >= 0,
      write_tries := integer() >= 0,
      write_waits := integer() >= 0,
      acc_success := integer() >= 0,
      acc_fails := integer() >= 0,
      acc_tries := integer() >= 0,
      acc_waits := integer() >= 0}

socket_info() =
    #{domain := domain() | integer(),
      type := type() | integer(),
      protocol := protocol() | integer(),
      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()}

in_addr() = {0..255, 0..255, 0..255, 0..255}
in6_addr() =
    {0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535,
     0..65535}

sockaddr_in() =
    #{family := inet,
      port := port_number(),
      addr := any | broadcast | loopback | in_addr()}

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

sockaddr_un() = #{family := local, path := binary() | string()}

The path element will always be a binary when returned from this module. When supplied to an API function in this module it may be a string(), which will be encoded into a binary according to the native file name encoding on the platform.

A terminating zero character will be appended before the address path is given to the OS, and the terminating zero will be stripped before giving the address path to the caller.

Linux's non-portable abstract socket address extension is handled by not doing any terminating zero processing in either direction, if the first byte of the address is zero.

sockaddr_ll() =
    #{family := packet,
      protocol := integer() >= 0,
      ifindex := integer(),
      pkttype := packet_type(),
      hatype := integer() >= 0,
      addr := binary()}

packet_type() =
    host | broadcast | multicast | otherhost | outgoing |
    loopback | user | kernel | fastroute |
    integer() >= 0

port_number() = 0..65535
in6_flow_info() = 0..1048575
in6_scope_id() = 0..4294967295
msg_flag() =
    cmsg_cloexec | confirm | ctrunc | dontroute | eor | errqueue |
    more | oob | peek | trunc

Flags corresponding to the message flag constants on the platform. The flags are lowercase and the constants are uppercase with the prefix MSG_.

Some flags are only used for sending, some only for receiving, some in received control messages, and some for several of these. Not all flags are supported on all platforms. See the platform's documentation.

sockopt_level() = socket | ip | ipv6 | tcp | udp | sctp

The OS protocol levels for socket options with the following names in OS header files:

socket
SOL_SOCKET with options named SO_*.
ip
IPPROTO_IP a.k.a SOL_IP with options named IP_*.
ipv6
IPPROTO_IPV6 a.k.a SOL_IPV6 with options named IPV6_*.
tcp
IPPROTO_TCP with options named TCP_*.
udp
IPPROTO_UDP with options named UDP_*.
sctp
IPPROTO_SCTP with options named SCTP_*.

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

These are socket options for the otp protocol level, that is {otp, Name} options, above all OS protocol levels. They affect Erlang/OTP's socket implementation.

debug
boolean() - Activate debug printout.
iow
boolean() - Inform On Wrap of statistics counters.
controlling_process
pid() - The socket "owner". Only the current controlling process can set this option.
rcvbuf
BufSize :: (default | integer()>0) | {N :: integer()>0, BufSize :: (default | integer()>0)} - Receive buffer size. The value default is only valid to set. N specifies the number of read attempts to do in a tight loop before assuming no more data is pending.
rcvctrlbuf
BufSize :: (default | integer()>0) - Buffer size for received ancillary messages. The value default is only valid to set.
sndctrlbuf
BufSize :: (default | integer()>0) - Buffer size for sent ancillary messages. The value default is only valid to set.
fd
integer() - Only valid to get. The OS protocol levels' socket descriptor. Functions open/1,2 can be used to create a socket according to this module from an existing OS socket descriptor.
use_registry
boolean() - Only valid to get. The value is set when the socket is created with open/2 or open/4.

Options not described here are intentionally undocumented and for Erlang/OTP internal use only.

socket_option() =
    {Level :: socket,
     Opt ::
         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} |
    {Level :: ip,
     Opt ::
         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 | recvdstaddr | recverr | recvif | recvopts |
         recvorigdstaddr | recvtos | recvttl | retopts |
         router_alert | sndsrcaddr | tos | transparent | ttl |
         unblock_source} |
    {Level :: ipv6,
     Opt ::
         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} |
    {Level :: tcp,
     Opt ::
         congestion | cork | info | keepcnt | keepidle |
         keepintvl | maxseg | md5sig | nodelay | noopt | nopush |
         syncnt | user_timeout} |
    {Level :: udp, Opt :: cork} |
    {Level :: sctp,
     Opt ::
         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}

Socket option on the form {Level, Opt} where the OS protocol Level = sockopt_level() and Opt is a socket option on that protocol level.

The OS name for an options is, except where otherwise noted, the Opt atom, in capitals, with prefix according to sockopt_level().

Note

See the OS documentation for every socket option.

An option below that has the value type boolean() will translate the value false to a C int with value 0, and the value true to !!0 (not (not false)).

An option with value type integer() will be translated to a C int that may have a restricted range, for example byte: 0..255. See the OS documentation.

Options for protocol level socket:

{socket, acceptconn}

Value = boolean()

{socket, bindtodevice}

Value = string()

{socket, broadcast}

Value = boolean()

{socket, debug}

Value = integer()

{socket, domain}

Value = domain()

Only valid to get.

The socket's protocol domain. Does not work on for instance FreeBSD.

{socket, dontroute}

Value = boolean()

{socket, keepalive}

Value = boolean()

{socket, linger}

Value = abort | linger()

The value abort is shorthand for #{onoff => true, linger => 0}, and only valid to set.

{socket, oobinline}

Value = boolean()

{socket, passcred}

Value = boolean()

{socket, peek_off}

Value = integer()

Currently disabled due to a possible infinite loop when calling recv/1-4 with peek in Flags.

{socket, priority}

Value = integer()

{socket, protocol}

Value = protocol()

Only valid to get.

The socket's protocol. Does not work on for instance Darwin.

{socket, rcvbuf}

Value = integer()

{socket, rcvlowat}

Value = integer()

{socket, rcvtimeo}

Value = timeval()

This option is unsupported per default; OTP has to be explicitly built with the --enable-esock-rcvsndtimeo configure option for this to be available.

Since our implementation uses nonblocking sockets, it is unknown if and how this option works, or even if it may cause malfunction. Therefore, we do not recommend setting this option.

Instead, use the Timeout argument to, for instance, the recv/3 function.

{socket, reuseaddr}

Value = boolean()

{socket, reuseport}

Value = boolean()

{socket, sndbuf}

Value = integer()

{socket, sndlowat}

Value = integer()

{socket, sndtimeo}

Value = timeval()

This option is unsupported per default; OTP has to be explicitly built with the --enable-esock-rcvsndtimeo configure option for this to be available.

Since our implementation uses nonblocking sockets, it is unknown if and how this option works, or even if it may cause malfunction. Therefore, we do not recommend setting this option.

Instead, use the Timeout argument to, for instance, the send/3 function.

{socket, timestamp}

Value = boolean()

{socket, type}

Value = type()

Only valid to get.

The socket's type.

Options for protocol level ip:

{ip, add_membership}

Value = ip_mreq()

Only valid to set.

{ip, add_source_membership}

Value = ip_mreq_source()

Only valid to set.

{ip, block_source}

Value = ip_mreq_source()

Only valid to set.

{ip, drop_membership}

Value = ip_mreq()

Only valid to set.

{ip, drop_source_membership}

Value = ip_mreq_source()

Only valid to set.

{ip, freebind}

Value = boolean()

{ip, hdrincl}

Value = boolean()

{ip, minttl}

Value = integer()

{ip, msfilter}

Value = null | ip_msfilter()

Only valid to set.

The value null passes a NULL pointer and size 0 to the C library call.

{ip, mtu}

Value = integer()

Only valid to get.

{ip, mtu_discover}

Value = ip_pmtudisc() | integer()

An integer() value is according to the platform's header files.

{ip, multicast_all}

Value = boolean()

{ip, multicast_if}

Value = any | in_addr()

{ip, multicast_loop}

Value = boolean()

{ip, multicast_ttl}

Value = integer()

{ip, nodefrag}

Value = boolean()

{ip, pktinfo}

Value = boolean()

{ip, recvdstaddr}

Value = boolean()

{ip, recverr}

Value = boolean()

{ip, recvif}

Value = boolean()

{ip, recvopts}

Value = boolean()

{ip, recvorigdstaddr}

Value = boolean()

{ip, recvtos}

Value = boolean()

{ip, recvttl}

Value = boolean()

{ip, retopts}

Value = boolean()

{ip, router_alert}

Value = integer()

{ip, sendsrcaddr}

Value = boolean()

{ip, tos}

Value = ip_tos() | integer()

An integer() value is according to the platform's header files.

{ip, transparent}

Value = boolean()

{ip, ttl}

Value = integer()

{ip, unblock_source}

Value = ip_mreq_source()

Only valid to set.

Options for protocol level ipv6:

{ipv6, addrform}

Value = domain()

As far as we know the only valid value is inet and it is only allowed for an IPv6 socket that is connected and bound to an IPv4-mapped IPv6 address.

{ipv6, add_membership}

Value = ipv6_mreq()

Only valid to set.

{ipv6, authhdr}

Value = boolean()

{ipv6, drop_membership}

Value = ipv6_mreq()

Only valid to set.

{ipv6, dstopts}

Value = boolean()

{ipv6, flowinfo}

Value = boolean()

{ipv6, hoplimit}

Value = boolean()

{ipv6, hopopts}

Value = boolean()

{ipv6, mtu}

Value = integer()

{ipv6, mtu_discover}

Value = ipv6_pmtudisc() | integer()

An integer() value is according to the platform's header files.

{ipv6, multicast_hops}

Value = ipv6_hops()

{ipv6, multicast_if}

Value = integer()

{ipv6, multicast_loop}

Value = boolean()

{ipv6, recverr}

Value = boolean()

{ipv6, recvhoplimit}

Value = boolean()

{ipv6, recvpktinfo}

Value = boolean()

{ipv6, recvtclass}

Value = boolean()

{ipv6, router_alert}

Value = integer()

{ipv6, rthdr}

Value = boolean()

{ipv6, tclass}

Value = boolean()

{ipv6, unicast_hops}

Value = ipv6_hops()

{ipv6, v6only}

Value = boolean()

Options for protocol level sctp. See also RFC 6458.

{sctp, associnfo}

Value = sctp_assocparams()

{sctp, autoclose}

Value = integer()

{sctp, disable_fragments}

Value = boolean()

{sctp, events}

Value = sctp_event_subscribe()

Only valid to set.

{sctp, initmsg}

Value = sctp_initmsg()

{sctp, maxseg}

Value = integer()

{sctp, nodelay}

Value = boolean()

{sctp, rtoinfo}

Value = sctp_rtoinfo()

Options for protocol level tcp:

{tcp, congestion}

Value = string()

{tcp, cork}

Value = boolean()

{tcp, maxseg}

Value = integer()

{tcp, nodelay}

Value = boolean()

Options for protocol level udp:

{udp, cork}

Value = boolean()

linger() = #{onoff := boolean(), linger := integer() >= 0}

Corresponds to the C struct linger for managing the socket option {socket, linger}.

timeval() = #{sec := integer(), usec := integer()}

Corresponds to the C struct timeval. The field sec holds seconds, and usec microseconds.

ip_mreq() = #{multiaddr := in_addr(), address := in_addr()}

Corresponds to the C struct ip_mreq for managing multicast groups.

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

Corresponds to the C struct ip_mreq_source for managing multicast groups.

ip_msfilter() =
    #{multiaddr := in_addr(),
      interface := in_addr(),
      mode := include | exclude,
      slist := [in_addr()]}

Corresponds to the C struct ip_msfilter for managing multicast source filtering (RFC 3376).

ip_pmtudisc() = want | dont | do | probe

Lowercase atom() values corresponding to the C library constants IP_PMTUDISC_*. Some constant(s) may be unsupported by the platform.

ip_tos() = lowdelay | throughput | reliability | mincost

Lowercase atom() values corresponding to the C library constants IPTOS_*. Some constant(s) may be unsupported by the platform.

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

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

Corresponds to the C struct ipv6_mreq for managing multicast groups. See also RFC 2553.

ipv6_hops() = default | 0..255

The value default is only valid to set and is translated to the C value -1, meaning the route default.

ipv6_pmtudisc() = want | dont | do | probe

Lowercase atom() values corresponding to the C library constants IPV6_PMTUDISC_*. Some constant(s) may be unsupported by the platform.

ipv6_pktinfo() = #{addr := in6_addr(), ifindex := integer()}
sctp_assocparams() =
    #{assoc_id := integer(),
      asocmaxrxt := 0..65535,
      numbe_peer_destinations := 0..65535,
      peer_rwnd := 0..4294967295,
      local_rwnd := 0..4294967295,
      cookie_life := 0..4294967295}

Corresponds to the C struct sctp_assocparams.

sctp_event_subscribe() =
    #{data_io := boolean(),
      association := boolean(),
      address := boolean(),
      send_failure := boolean(),
      peer_error := boolean(),
      shutdown := boolean(),
      partial_delivery := boolean(),
      adaptation_layer => boolean(),
      sender_dry => boolean()}

Corresponds to the C struct sctp_event_subscribe.

Not all fields are implemented on all platforms; unimplemented fields are ignored, but implemented fields are mandatory. Note that the '_event' suffixes have been stripped from the C struct field names, for convenience.

sctp_initmsg() =
    #{num_ostreams := 0..65535,
      max_instreams := 0..65535,
      max_attempts := 0..65535,
      max_init_timeo := 0..65535}

Corresponds to the C struct sctp_initmsg.

sctp_rtoinfo() =
    #{assoc_id := integer(),
      initial := 0..4294967295,
      max := 0..4294967295,
      min := 0..4294967295}

Corresponds to the C struct sctp_rtoinfo.

msghdr() =
    #{addr => sockaddr(),
      iov := [binary()],
      ctrl =>
          [cmsghdr_recv() |
           #{level := sockopt_level() | integer(),
             type := integer(),
             data := binary()}] |
          [cmsghdr_send() |
           #{level := sockopt_level() | integer(),
             type := integer(),
             data := binary()}],
      flags => [msg_flag()]}

Corresponds to the C struct msghdr, see your platform documentation for sendmsg(2) and recvmsg(2).

addr
Optional peer address, used on non-connected sockets.
iov
Mandatory data as a list of binaries.
ctrl
Control messages (CMSG). Optional for sendmsg/2,3,4. At least an empty list is returned by recvmsg/1,2,3,5.
iov
Message flags. Ignored by sendmsg/2,3,4. Returned by recvmsg/1,2,3,5.

A control message can be specified with symbolic or native integer level, integer type and binary data. The application is responsible for figuring out the correct integer values and data for the runtime platform.

cmsghdr_recv() =
    #{level := socket,
      type := timestamp,
      data := timeval() | binary()} |
    #{level := socket, type := rights, data := binary()} |
    #{level := socket, type := credentials, data := binary()} |
    #{level := ip,
      type := tos,
      data := ip_tos() | integer() | binary()} |
    #{level := ip,
      type := recvtos,
      data := ip_tos() | integer() | binary()} |
    #{level := ip, type := ttl, data := integer() | binary()} |
    #{level := ip, type := recvttl, data := integer() | binary()} |
    #{level := ip,
      type := pktinfo,
      data := ip_pktinfo() | binary()} |
    #{level := ip,
      type := origdstaddr,
      data := sockaddr_in() | binary()} |
    #{level := ip,
      type := recverr,
      data := extended_err() | binary()} |
    #{level := ipv6,
      type := hoplimit,
      data := integer() | binary()} |
    #{level := ipv6,
      type := pktinfo,
      data := ipv6_pktinfo() | binary()} |
    #{level := ipv6,
      type := recverr,
      data := extended_err() | binary()} |
    #{level := ipv6, type := tclass, data := integer() | binary()}

Control messages (ancillary messages) generated by recvmsg/1,2,3,5.

Control messages data fields with symbolic values (atom()s) also may have integer() or even binary() values, that match the platform's header files.

cmsghdr_send() =
    #{level := socket, type := timestamp, data := binary()} |
    #{level := socket, type := rights, data := binary()} |
    #{level := socket, type := credentials, data := binary()} |
    #{level := ip,
      type := tos,
      data := ip_tos() | integer() | binary()} |
    #{level := ip, type := ttl, data := integer() | binary()} |
    #{level := ipv6, type := tclass, data := integer() | binary()}

Control messages (ancillary messages) accepted by sendmsg/2,3,4.

Control messages data fields with symbolic values (atom()s) also may have integer() or even binary() values, that match the platform's header files.

icmp_dest_unreach() =
    net_unreach | host_unreach | port_unreach | frag_needed |
    net_unknown | host_unknown

icmpv6_dest_unreach() =
    noroute | adm_prohibited | not_neighbour | addr_unreach |
    port_unreach | policy_fail | reject_route

ee_origin() = none | local | icmp | icmp6
extended_err() =
    #{error := posix(),
      origin := icmp,
      type := dest_unreach,
      code := icmp_dest_unreach() | 0..255,
      info := 0..4294967295,
      data := 0..4294967295,
      offender := undefined | sockaddr()} |
    #{error := posix(),
      origin := icmp,
      type := time_exceeded | 0..255,
      code := 0..255,
      info := 0..4294967295,
      data := 0..4294967295,
      offender := undefined | sockaddr()} |
    #{error := posix(),
      origin := icmp6,
      type := dest_unreach,
      code := icmpv6_dest_unreach() | 0..255,
      info := 0..4294967295,
      data := 0..4294967295,
      offender := undefined | sockaddr()} |
    #{error := posix(),
      origin := icmp6,
      type := pkt_toobig | time_exceeded | 0..255,
      code := 0..255,
      info := 0..4294967295,
      data := 0..4294967295,
      offender := undefined | sockaddr()} |
    #{error := posix(),
      origin := ee_origin() | 0..255,
      type := 0..255,
      code := 0..255,
      info := 0..4294967295,
      data := 0..4294967295,
      offender := undefined | sockaddr()}

The POSIX error codes originates from the OS level socket interface.

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 = posix() | closed | invalid | timeout

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.

accept(LSocket, Timeout :: nowait) ->
          {ok, Socket} | {select, SelectInfo} | {error, Reason}
OTP 22.1
accept(LSocket, SelectHandle) ->
          {ok, Socket} | {select, SelectInfo} | {error, Reason}
OTP @OTP-16749@

Types

LSocket = Socket = socket()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason = posix() | closed | invalid

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 {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when a client connects. A subsequent call to accept/1,2 will then return the socket.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

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

Types

Socket = socket()
Addr = sockaddr() | any | broadcast | loopback
Reason = posix() | closed | invalid

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.

cancel(Socket, SelectInfo) -> ok | {error, Reason}
OTP 22.1

Types

Socket = socket()
SelectInfo = select_info()
Reason = closed | invalid

Cancel an asynchronous request.

Call this function in order to cancel a previous asynchronous call to, e.g. recv/3.

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

Types

Socket = socket()
Reason = posix() | closed | timeout

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 = posix() | closed | invalid | already | timeout

This function connects the socket to the address specified by the SockAddr argument, and returns when the connection has been established or when the Timeout has expired.

connect(Socket, SockAddr, Timeout :: nowait) ->
           ok | {select, SelectInfo} | {error, Reason}
OTP 22.1
connect(Socket, SockAddr, SelectHandle) ->
           ok | {select, SelectInfo} | {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
SockAddr = sockaddr()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason = posix() | closed | invalid | already

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

In the case when its not possible to immediately establish a connection, the function will return {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when the connection is completed. A subsequent call to connect/1 will then finalize the connection.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

connect(Socket) -> ok | {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
Reason = posix() | closed | invalid | already

This function finalizes a connection initiation on a socket, after calling connect(_, _, nowait | select_handle()) that returned {select, SelectInfo} and after receiving the select message {'$socket', Socket, select, SelectHandle}, and returns whether the connection was succesful or not.

Instead of calling this function, for backwards compatibility, it is allowed to call connect/2,3, but that incurs more overhead since the connect address and timeout are processed in vain.

getopt(X1 :: socket(),
       SocketOption :: {Level :: otp, Opt :: otp_socket_option()}) ->
          {ok, Value :: term()} | {error, invalid | closed}
OTP 22.0

Gets a socket option from the protocol level otp, which is this implementation's level above the OS protocol layers.

See the type otp_socket_option() for a description of the options on this level.

getopt(X1 :: socket(), SocketOption :: socket_option()) ->
          {ok, Value :: term()} |
          {error, posix() | invalid | closed}
OTP 22.0

Gets a socket option from one of the OS's protocol levels. See the type socket_option() for which options that this implementation knows about, how they are related to option names in the OS, and if there are known pecularities with any of them.

What options are valid depends 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, nor possible to get, on all platforms. That is, even if "we" support an option; it does not mean that the underlying OS does.

OTP 22.0

Types

Socket = socket()
Reason = inet:posix() | invalid | closed

Backwards compatibility function.

The same as getopt(Socket, {Level, Opt})

getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level ::
                       sockopt_level() |
                       (NativeLevel :: integer() >= 0),
                   NativeOpt :: integer() >= 0},
              ValueType :: integer) ->
                 {ok, Value :: integer()} |
                 {error, posix() | invalid | closed}
OTP 22.0
getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level ::
                       sockopt_level() |
                       (NativeLevel :: integer() >= 0),
                   NativeOpt :: integer() >= 0},
              ValueType :: boolean) ->
                 {ok, Value :: boolean()} |
                 {error, posix() | invalid | closed}
OTP 22.0
getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level ::
                       sockopt_level() |
                       (NativeLevel :: integer() >= 0),
                   NativeOpt :: integer() >= 0},
              ValueSize :: integer() >= 0) ->
                 {ok, Value :: binary()} |
                 {error, posix() | invalid | closed}
OTP 22.0
getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level ::
                       sockopt_level() |
                       (NativeLevel :: integer() >= 0),
                   NativeOpt :: integer() >= 0},
              ValueSpec :: binary()) ->
                 {ok, Value :: binary()} |
                 {error, posix() | invalid | closed}
OTP 24.0

Gets a socket option that may be unknown to our implementation, or that has a type not compatible with our implementation, that is; in "native mode".

The socket option may be specified with an ordinary socket_option() tuple, with a known Level = sockopt_level() and an integer NativeOpt, or with both an integer NativeLevel and NativeOpt.

How to decode the option value has to be specified either with ValueType, by specifying the ValueSize for a binary() that will contain the fetched option value, or by specifying a binary() ValueSpec that will be copied to a buffer for the getsockopt() call to write the value in which will be returned as a new binary().

If ValueType is integer a C type (int) will be fetched, if it is boolean a C type (int) will be fetched and converted into a boolean() according to the C implementation.

What options are valid depends on what kind of socket it is (domain(), type() and protocol()).

The integer values for NativeLevel and NativeOpt as well as the Value encoding has to be deduced from the header files for the running system.

info(Socket) -> socket_info()
OTP 22.1

Types

Socket = socket()

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.

Note

In order to ensure data integrity, mutex'es are taken when needed. So, do not call this function often.

is_supported(Key1 :: term()) -> boolean()
OTP 23.0
is_supported(Key1 :: term(), Key2 :: term()) -> boolean()
OTP 23.0

This function retreives information about what the platform supports, such as if SCTP is supported, or if a socket options are supported.

For keys other than the known false is returned. Note that in a future version or on a different platform there might be more supported items.

This functions returns a boolean corresponding to what supports/0-2 reports for the same Key1 (and Key2).

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

Types

Socket = socket()
Backlog = integer()
Reason = posix() | closed

Listen for connections on a socket.

number_of() -> integer() >= 0
OTP 22.3

Returns the number of active sockets.

open(FD) -> {ok, Socket} | {error, Reason}
OTP 23.0
open(FD, Opts) -> {ok, Socket} | {error, Reason}
OTP 23.0

Types

FD = integer()
Opts =
    #{domain => domain() | integer(),
      type => type() | integer(),
      protocol => protocol() | integer(),
      dup => boolean(),
      debug => boolean(),
      use_registry => boolean()}
Socket = socket()
Reason = posix() | domain | type | protocol

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:

domain => domain() | integer()

Which domain is the descriptor of.

See also open/2,3,4.

type => type() | integer()

Which type is the descriptor of.

See also open/2,3,4.

protocol => protocol() | integer()

Which protocol is the descriptor of.

See also open/2,3,4.

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.

use_registry: boolean()

Enable or disable use of the socket registry for this socket. This overrides the global value.
Defaults to the global value, see use_registry/1.

Note

This function should be used with care!

On some platforms its necessary to provide the protocol as its impossible to retrieve it.

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

Types

Domain = domain() | integer()
Type = type() | integer()
Protocol = protocol() | integer()
Opts =
    #{netns => string(),
      debug => boolean(),
      use_registry => boolean()}
Socket = socket()
Reason = posix() | protocol

Creates an endpoint (socket) for communication.

Domain and Type may be integer()s, as defined in the platform's header files. The same goes for Protocol but according to the platform's services(5) database. See the OS man page for the library call socket(2)

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 specified, it must be default.

The Opts argument is intended for "other" options. The supported option(s) are described below:

netns: string()

Used to set the network namespace during the open call. Only supported on the Linux platform.

debug: boolean()

Enable or disable debug during the open call.
Defaults to false.

use_registry: boolean()

Enable or disable use of the socket registry for this socket. This overrides the global value.
Defaults to the global value, see use_registry/1.

Note

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.

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

Types

Socket = socket()
SockAddr = sockaddr()
Reason = posix() | closed | bad_data

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 = [msg_flag()]
Timeout = timeout()
Data = binary()
Reason =
    posix() |
    closed | invalid | timeout |
    {posix() | closed | invalid | timeout, Data :: binary()}

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

recv(Socket, Length, Flags :: nowait) ->
        {ok, Data} |
        {ok, {Data, SelectInfo}} |
        {select, SelectInfo} |
        {error, Reason}
OTP 22.1
recv(Socket, Length, SelectHandle) ->
        {ok, Data} |
        {ok, {Data, SelectInfo}} |
        {select, SelectInfo} |
        {error, Reason}
OTP @OTP-16749@
recv(Socket, Length, Flags, Timeout :: nowait) ->
        {ok, Data} |
        {ok, {Data, SelectInfo}} |
        {select, SelectInfo} |
        {error, Reason}
OTP 22.1
recv(Socket, Length, Flags, SelectHandle) ->
        {ok, Data} |
        {ok, {Data, SelectInfo}} |
        {select, SelectInfo} |
        {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
Length = integer() >= 0
Flags = [msg_flag()]
Data = binary()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason =
    posix() |
    closed | invalid |
    {posix() | closed | invalid, Data :: binary()}

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 {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when data has arrived. A subsequent call to accept/1,2 will then return the data.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

Note that if a length (> 0) is specified, and only part of that amount of data is available, the function will return {ok, {Data, SelectInfo with partial data. If the caller doesn't want to wait for the remaining data, it must call cancel/2.

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 = [msg_flag()]
Timeout = timeout()
Source = sockaddr() | undefined
Data = binary()
Reason = posix() | closed | invalid | timeout

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.

recvfrom(Socket, Flags, Timeout :: nowait) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}
OTP 22.1
recvfrom(Socket, Flags, SelectHandle) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}
OTP @OTP-16749@
recvfrom(Socket, BufSz, Flags) ->
            {ok, {Source, Data}} | {error, Reason}
OTP 22.1
recvfrom(Socket, BufSz, Timeout :: nowait) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}
OTP @OTP-16749@
recvfrom(Socket, BufSz, Flags, Timeout :: nowait) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}
OTP 22.1
recvfrom(Socket, BufSz, Flags, SelectHandle) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
BufSz = integer() >= 0
Flags = [msg_flag()]
Source = sockaddr() | undefined
Data = binary()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason = posix() | closed | invalid

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 {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when data has arrived. A subsequent call to recvfrom/1-4 will then return the data.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

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 = [msg_flag()]
Timeout = timeout()
MsgHdr = msghdr()
Reason = posix() | closed | invalid | timeout

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.

recvmsg(Socket, Timeout :: nowait) ->
           {ok, MsgHdr} | {select, SelectInfo} | {error, Reason}
OTP 22.1
recvmsg(Socket, Timeout :: SelectHandle) ->
           {ok, MsgHdr} | {select, SelectInfo} | {error, Reason}
OTP @OTP-16749@
recvmsg(Socket, Flags, Timeout :: nowait) ->
           {ok, MsgHdr} | {select, SelectInfo} | {error, Reason}
OTP 22.1
recvmsg(Socket, Flags, SelectHandle) ->
           {ok, MsgHdr} | {select, SelectInfo} | {error, Reason}
OTP @OTP-16749@
recvmsg(Socket, BufSz, CtrlSz, Flags, Timeout :: nowait) ->
           {ok, MsgHdr} | {select, SelectInfo} | {error, Reason}
OTP 22.1
recvmsg(Socket, BufSz, CtrlSz, Flags, SelectHandle) ->
           {ok, MsgHdr} | {select, SelectInfo} | {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
BufSz = CtrlSz = integer() >= 0
Flags = [msg_flag()]
MsgHdr = msghdr()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason = posix() | closed | invalid

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 {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when data has arrived. A subsequent call to recvmsg/1-3,5 will then return the data.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

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 = [msg_flag()]
Timeout = timeout()
Reason =
    {posix() | closed | invalid | timeout,
     Remaining :: integer() >= 1}

Send a message on a connected socket.

send(Socket, Data, Flags :: nowait) ->
        ok |
        {select, SelectInfo} |
        {ok, {RestData, SelectInfo}} |
        {error, Reason}
OTP 22.1
send(Socket, Data, SelectHandle) ->
        ok |
        {select, SelectInfo} |
        {ok, {RestData, SelectInfo}} |
        {error, Reason}
OTP @OTP-16749@
send(Socket, Data, Flags, Timeout :: nowait) ->
        ok |
        {select, SelectInfo} |
        {ok, {RestData, SelectInfo}} |
        {error, Reason}
OTP 22.1
send(Socket, Data, Flags, SelectHandle) ->
        ok |
        {select, SelectInfo} |
        {ok, {RestData, SelectInfo}} |
        {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
Data = iodata()
Flags = [msg_flag()]
RestData = binary()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason =
    {posix() | closed | invalid, Remaining :: integer() >= 1}

Send a message on a connected socket.

In the case when there is no room in the (system-) buffers, the function will return {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when there is room for more data A subsequent call to send/2-4 will then send the data.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

Note that if not all the data was sent, the function will return {ok, {RestData, SelectInfo} If the caller does not want to wait to be able to send the rest, it should call cancel/2.

sendmsg(Socket, MsgHdr) -> ok | {ok, Remaining} | {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 = [msg_flag()]
Timeout = timeout()
Remaining = erlang:iovec()
Reason = posix() | closed | timeout

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

sendmsg(Socket, MsgHdr, Flags :: nowait) ->
           ok |
           {ok, Remaining} |
           {select, SelectInfo} |
           {error, Reason}
OTP 22.1
sendmsg(Socket, MsgHdr, SelectHandle) ->
           ok |
           {ok, Remaining} |
           {select, SelectInfo} |
           {error, Reason}
OTP @OTP-16749@
sendmsg(Socket, MsgHdr, Flags, Timeout :: nowait) ->
           ok |
           {ok, Remaining} |
           {select, SelectInfo} |
           {error, Reason}
OTP 22.1
sendmsg(Socket, MsgHdr, Flags, SelectHandle) ->
           ok |
           {ok, Remaining} |
           {select, SelectInfo} |
           {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
MsgHdr = msghdr()
Flags = [msg_flag()]
Remaining = erlang:iovec()
SelectInfo = select_info()
SelectHandle = select_handle()
Reason = posix() | closed

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 {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when there is room for more data A subsequent call to sendmsg/2-4 will then send the data.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

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 = sockaddr()
Flags = [msg_flag()]
Timeout = timeout()
Reason =
    {posix() | closed | invalid | timeout,
     Remaining :: integer() >= 1}

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

sendto(Socket, Data, Dest, Flags :: nowait) ->
          ok | {select, SelectInfo} | {error, Reason}
OTP 22.1
sendto(Socket, Data, Dest, SelectHandle) ->
          ok | {select, SelectInfo} | {error, Reason}
OTP @OTP-16749@
sendto(Socket, Data, Dest, Flags, Timeout :: nowait) ->
          ok |
          {ok, {binary(), SelectInfo}} |
          {select, SelectInfo} |
          {error, Reason}
OTP 22.1
sendto(Socket, Data, Dest, Flags, SelectHandle) ->
          ok |
          {ok, {binary(), SelectInfo}} |
          {select, SelectInfo} |
          {error, Reason}
OTP @OTP-16749@

Types

Socket = socket()
Data = binary()
Dest = sockaddr()
Flags = [msg_flag()]
SelectInfo = select_info()
SelectHandle = select_handle()
Reason =
    {posix() | closed | invalid, Remaining :: integer() >= 1}

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 {select, SelectInfo}. The caller will then receive a select message, {'$socket', Socket, select, SelectHandle} ( with SelectHandle from SelectInfo ) when there is room for more data A subsequent call to sendto/3-5 will then send the data.

If the timeout argument is a SelectHandle, this term will be in a returned SelectInfo and the corresponding select message. It is supposed to be a select_handle() unique to this call. If the timeout argument is nowait a new SelectHandle is generated.

setopt(Socket :: socket(),
       SocketOption :: {Level :: otp, Opt :: otp_socket_option()},
       Value :: term()) ->
          ok | {error, invalid | closed}
OTP 22.0

Sets a socket option in the protocol level otp, which is this implementation's level above the OS protocol layers.

See the type otp_socket_option() for a description of the options on this level.

setopt(Socket :: socket(),
       SocketOption :: socket_option(),
       Value :: term()) ->
          ok | {error, posix() | invalid | closed}
OTP 22.0

Set a socket option in one of the OS's protocol levels. See the type socket_option() for which options that this implementation knows about, how they are related to option names in the OS, and if there are known pecularities with any of them.

What options are valid depends 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, nor possible to set, on all platforms. That is, even if "we" support an option; it does not mean that the underlying OS does.

OTP 22.0

Types

Socket = socket()
Value = term()
Reason = inet:posix() | invalid | closed

Backwards compatibility function.

The same as setopt(Socket, {Level, Opt}, Value)

setopt_native(Socket :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level ::
                       sockopt_level() |
                       (NativeLevel :: integer() >= 0),
                   NativeOpt :: integer() >= 0},
              Value :: integer() | boolean() | binary()) ->
                 ok | {error, posix() | invalid | closed}
OTP 22.0

Sets a socket option that may be unknown to our implementation, or that has a type not compatible with our implementation, that is; in "native mode".

If Value is an integer() it will be used as a C type (int), if it is a boolean() it will be used as a C type (int) with the C implementations values for false or true, and if it is a binary() its content and size will be used as the option value.

The socket option may be specified with an ordinary socket_option() tuple, with a known Level = sockopt_level() and an integer NativeOpt, or with both an integer NativeLevel and NativeOpt.

What options are valid depends on what kind of socket it is (domain(), type() and protocol()).

The integer values for NativeLevel and NativeOpt as well as the encoding of Value has to be deduced from the header files for the running system.

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

Types

Socket = socket()
How = read | write | read_write
Reason = posix() | closed

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 = posix() | closed | bad_data

Returns the current address to which the socket is bound.

supports() ->
            [{Key1 :: term(),
              boolean() |
              [{Key2 :: term(),
                boolean() | [{Key3 :: term(), boolean()}]}]}]
OTP 22.0
supports(Key1 :: term()) ->
            [{Key2 :: term(),
              boolean() | [{Key3 :: term(), boolean()}]}]
OTP 22.0
supports(Key1 :: term(), Key2 :: term()) ->
            [{Key3 :: term(), boolean()}]
OTP 22.0

These functions function retreives information about what the platform supports, such which platform features or which socket options, are supported.

For keys other than the known the empty list is returned, Note that in a future version or on a different platform there might be more supported items.

supports()

Returns a list of {Key1, supports(Key1)} tuples for every Key1 described in supports/1 and {Key1, boolean()} tuples for each of the following keys:

sctp
SCTP support
ipv6
IPv6 support
local
Unix Domain sockets support (AF_UNIX | AF_LOCAL)
netns
Network Namespaces support (Linux, setns(2))

supports(msg_flags = Key1)

Returns a list of {Flag, boolean()} tuples for every Flag in msg_flag() with the boolean() indicating if the flag is supported on this platform.

supports(protocols = Key1)

Returns a list of {Name :: atom(), boolean()} tuples for every Name in protocol() with the boolean() indicating if the protocol is supported on this platform.

supports(options = Key1)

Returns a list of {SocketOption, boolean()} tuples for every SocketOption in socket_option() with the boolean() indicating if the socket option is supported on this platform.

supports(options = Key1, Key2)

For a Key2 in sockopt_level() returns a list of {Opt, boolean()} tuples for all known socket options Opt on that Level =:= Key2, and the boolean() indicating if the socket option is supported on this platform. See setopt/3 and getopt/2.

use_registry(D :: boolean()) -> ok
OTP 23.1

Globally change if the socket registry is to be used or not. Note that its still possible to override this explicitly when creating an individual sockets, see open/2 or open/4 for more info (use the Extra argument).

which_sockets() -> [socket()]
OTP 22.3
which_sockets(FilterRule) -> [socket()]
OTP 22.3

Types

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