socket(3erl)

🌸 socket 🌸

okay so bestie, welcome to the socket module β€” this is the Erlang Module Definition page for it, and it's a big one, so buckle up πŸŽ€


✨ NAME ✨

socket β€” the socket interface, literally πŸ’…


πŸ¦‹ DESCRIPTION πŸ¦‹

This module hands you an API for network sockets. You get functions to create, delete and manipulate sockets, plus send and receive data on them. iconic behavior honestly πŸ‘‘

The whole intent? It should be as "close as possible" to the OS level socket interface. The only significant addition is that some functions β€” like recv/3 β€” get a time-out argument. that's the one little treat we added πŸ’–

Note (read this one bestie): Some functions let you do an asynchronous call. You get that by setting the Timeout argument to nowait. So for example, if you call the recv/3 function with Timeout set to nowait (recv(Sock, 0, nowait)) and there's actually nothing to read, it'll come back with {select, SelectInfo} (and SelectInfo contains the SelectHandle). Then when data eventually shows up, a 'select' message gets sent to the caller:
{'$socket', socket(), select, SelectHandle}

The caller can now call the recv function again and probably expect data β€” but fr, it's really up to the OS network protocol implementation, no cap.

Also important: all other users are locked out until the 'current user' has called the function (in this case recv) and its return value shows the operation has completed. You can also cancel an operation with cancel/2. don't leave your besties hanging πŸ™ˆ

Instead of Timeout = nowait, it's equivalent to create a SelectHandle with make_ref() and give that as Timeout. Then that becomes the SelectHandle in the 'select' message, which enables a compiler optimization for receiving a message containing a newly created reference() β€” it gets to ignore the part of the message queue that had arrived before that reference() was created. fancy ✨

Another message you have to be prepared for when you make asynchronous calls is the abort message:

{'$socket', socket(), abort, Info}

This one means the (asynchronous) operation has been aborted. If, say, the socket got closed by another process, then Info will be {SelectHandle, closed}. πŸ’€

Note (the fine print, stay with me): There is currently no support for Windows. Support for IPv6 has been implemented but not tested. And SCTP has only been partly implemented (and not tested). so like… tread carefully 😭

🧚 DATA TYPES 🧚

invalid()

invalid() = {invalid, What :: term()}

domain()

domain() = inet | inet6 | local | unspec

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

The calls supports(), is_supported(ipv6) and is_supported(local) tell you if the IPv6 protocol for the inet6 protocol domain / address family is supported, and if the local protocol domain / address family is supported, by the platform's header files. iykyk 🌈

type()

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

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

protocol()

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.

See open/2,3,4.

The call supports(protocols) returns which protocols are supported, and is_supported(protocols, Protocol) tells you if Protocol is among the enumerated ones. πŸ’…

socket()

socket() = {'$socket', socket_handle()}

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

socket_handle()

An opaque socket handle, unique for the socket.

select_tag()

A tag that describes the (select) operation, contained in the returned select_info().

select_handle()

select_handle() = reference()

A reference() that uniquely identifies the (select) operation, contained in the returned select_info().

select_info()

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

Returned by an operation that requires the caller to wait for a select message containing the SelectHandle.

info()

info() =
    #{counters := #{atom() := integer() >= 0},
      iov_max := integer() >= 0,
      use_registry := boolean()}

The smallest allowed iov_max value according to POSIX is 16, but check your platform documentation to be sure. πŸ‘€

socket_counters()

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,
      sendfile => integer() >= 0,
      sendfile_byte => integer() >= 0,
      sendfile_fails => integer() >= 0,
      sendfile_max => integer() >= 0,
      sendfile_pkg => integer() >= 0,
      sendfile_pkg_max => integer() >= 0,
      sendfile_tries => integer() >= 0,
      sendfile_waits => integer() >= 0,
      acc_success := integer() >= 0,
      acc_fails := integer() >= 0,
      acc_tries := integer() >= 0,
      acc_waits := integer() >= 0}

info_keys()

info_keys() =
    [domain | type | protocol | fd | owner | local_address |
     remote_address | recv | sent | state]

Defines the information elements of the table(s) printed by the i/0, i/1 and i/2 functions. cute little table bestie πŸŽ€

socket_info()

socket_info() =
    #{domain := domain() | integer(),
      type := type() | integer(),
      protocol := protocol() | integer(),
      owner := 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(),
      rstates := [atom()],
      wstates := [atom()]}

in_addr()

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

in6_addr()

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

sockaddr()

sockaddr() =
    sockaddr_in() |
    sockaddr_in6() |
    sockaddr_un() |
    sockaddr_ll() |
    sockaddr_dl() |
    sockaddr_unspec() |
    sockaddr_native()

sockaddr_recv()

sockaddr_recv() = sockaddr() | binary()

sockaddr_in()

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

sockaddr_in6()

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

sockaddr_un()

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

The path element will always be a binary when returned from this module. When you supply it 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 gets appended before the address path is given to the OS, and the terminating zero gets stripped before giving the address path to the caller. so polite of it 🫢

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. sneaky but valid πŸ’…

sockaddr_ll()

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

sockaddr_dl()

sockaddr_dl() =
    #{family := link,
      index := integer() >= 0,
      type := integer() >= 0,
      nlen := integer() >= 0,
      alen := integer() >= 0,
      slen := integer() >= 0,
      data := binary()}

sockaddr_unspec()

sockaddr_unspec() = #{family := unspec, addr := binary()}

sockaddr_native()

sockaddr_native() = #{family := integer(), addr := binary()}

packet_type()

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

hatype()

hatype() =
    netrom | eether | ether | ax25 | pronet | chaos | ieee802 |
    arcnet | appletlk | dlci | atm | metricom | ieee1394 | eui64 |
    infiniband | tunnel | tunnel6 | loopback | localtlk | none |
    void |
    integer() >= 0

port_number()

port_number() = 0..65535

in6_flow_info()

in6_flow_info() = 0..1048575

in6_scope_id()

in6_scope_id() = 0..4294967295

msg_flag()

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. Check the platform's documentation, supports(msg_flags), and is_supported(msg_flags, MsgFlag). fr fr, don't assume πŸ”₯

level()

level() = socket | protocol()

The OS protocol levels for, like, socket options and control messages, with the following names in the 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_*.

There are many other possible protocols, but the ones above are the ones this socket library actually implements socket options and/or control messages for. πŸ‘‘

All protocols known to the OS are enumerated when the Erlang VM is started. See the OS man page for protocols(5). The protocol level socket is always implemented as SOL_SOCKET and all the others mentioned in the list above are valid, if supported by the platform, whether they're enumerated or not.

The calls supports() and is_supported(protocols, Protocol) can be used to find out if protocols ipv6 and/or sctp are supported according to the platform's header files. 🌈

otp_socket_option()

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 β€” sitting above all the OS protocol levels. They affect Erlang/OTP's socket implementation. main character behavior honestly ✨

  • debug β€” boolean() β€” Activate debug printout.

okay that's the types done, more coming in the next part bestie, don't go anywhere πŸ’œ

okay so, picking up right in the middle of the option-map fields, bestie β€” here's the rest of that type tea β˜•βœ¨

  • 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 β€” so don't ask, bestie, it's giving secret menu. πŸ™ˆ

here's the whole socket_option() shape, no cap:

       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}

so a socket option is on the form {Level, Opt} where the OS protocol Level = level() and Opt is a socket option on that protocol level. πŸ’…

the OS name for an option is β€” except where otherwise noted β€” the Opt atom, in capitals, with a prefix according to level(). iykyk.

Note: the IPv6 option pktoptions is a special (barf) case. It is intended for backward compatibility usage only. Do not use this option. πŸ’€πŸš«
Note: see the OS documentation for every socket option. fr fr, every single one.

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)). 😭 iconic C nonsense.

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

the calls supports(options), supports(options, Level) and is_supported(options, {Level, Opt}) can be used to find out which socket options that are supported by the platform. πŸ•΅οΈβ€β™€οΈβœ¨

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. πŸ’€ don't do it.
  • {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()
Warning! When this option is enabled, error messages may arrive on the socket's error queue, which should be read using the message flag errqueue, and using recvmsg/1,2,3,4,5 to get all error information in the message's ctrl field as a control message #{level := ip, type := recverr}. 🚨
A working strategy should be to first poll the error queue using recvmsg/2,3,4 with Timeout =:= 0 and Flags containing errqueue (ignore the return value {error, timeout}) before reading the actual data to ensure that the error queue gets cleared. And read the data using one of the nowait | select_handle() recv functions: recv/3,4, recvfrom/3,4 or recvmsg/3,4,5. Otherwise you might accidentally cause a busy loop in and out of 'select' for the socket. πŸ’…πŸ”₯
  • {ip, recvif} β€” Value = boolean() β€” ask the kernel to tell you which interface a packet showed up on πŸ›¬
  • {ip, recvopts} β€” Value = boolean() β€” want the IP options back? say yes here
  • {ip, recvorigdstaddr} β€” Value = boolean() β€” hand over the original destination address of the packet, fr
  • {ip, recvtos} β€” Value = boolean() β€” get the TOS field delivered to you
  • {ip, recvttl} β€” Value = boolean() β€” same energy, but for the TTL
  • {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, so like, it's whatever your headers say it is
  • {ip, transparent} β€” Value = boolean()
  • {ip, ttl} β€” Value = integer()
  • {ip, unblock_source} β€” Value = ip_mreq_source() β€” ⚠️ only valid to set, don't come at it trying to read

🌐 Options for protocol level ipv6

  • {ipv6, addrform} β€” Value = domain() β€” as far as we know the only valid value is inet, and it's 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() β€” 🚨 Warning! See the socket option {ip, recverr} regarding the socket's error queue. The same warning applies for this option. Not playing around with this one.
  • {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, bestie

  • {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}. It's giving "do I actually wait for my data to flush" energy πŸ‘‘

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

Corresponds to the C struct timeval. The field sec holds seconds, and usec microseconds. Tiny units, huge drama 🫢

πŸ“‘ ip_mreq() = #{multiaddr := in_addr(), interface := 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). Filtering but make it iconic ✨

πŸ” ip_pmtudisc() = want | dont | do | probe

Lowercase atom() values corresponding to the C library constants IP_PMTUDISC_*. Heads up: 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 it's translated to the C value -1, meaning the route default. Like, "let the router decide", periodt πŸ’…

πŸ”₯ 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()}

Corresponds to the C struct sctp_assocparams. (Yes, numbe_peer_destinations β€” that's literally how it's spelled here, don't @ me 😭)

πŸŽ€ 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. And ngl, 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.


πŸ“¨ msg() = msg_send() | msg_recv()

πŸ’Œ msg_send() = #{addr => sockaddr(), iov := erlang:iovec(), ctrl => [cmsg_send() | #{level := level() | integer(), type := integer(), data := binary()}]}

Message sent by sendmsg/2,3,4.

Corresponds to a C struct msghdr β€” see your platform documentation for sendmsg(2).

  • addr β€” Optional peer address, used on unconnected sockets. Corresponds to msg_name and msg_namelen fields of a struct msghdr. If not used they are set to NULL, 0.
  • iov β€” Mandatory data as a list of binaries. The msg_iov and msg_iovlen fields of a struct msghdr.
  • ctrl β€” Optional list of control messages (CMSG). Corresponds to the msg_control and msg_controllen fields of a struct msghdr. If not used they are set to NULL, 0.

The msg_flags field of the struct msghdr is set to 0.

πŸ“¬ msg_recv() = #{addr => sockaddr_recv(), iov := erlang:iovec(), ctrl := [cmsg_recv() | #{level := level() | integer(), type := integer(), data := binary()}], flags := [msg_flag() | integer()]}

Message returned by recvmsg/1,2,3,5.

Corresponds to a C struct msghdr β€” see your platform documentation for recvmsg(2).

  • addr β€” Optional peer address, used on unconnected sockets. Corresponds to msg_name and msg_namelen fields of a struct msghdr. If NULL the map key is not present.
  • iov β€” Data as a list of binaries. The msg_iov and msg_iovlen fields of a struct msghdr.
  • ctrl β€” A possibly empty list of control messages (CMSG). Corresponds to the msg_control and msg_controllen fields of a struct msghdr.
  • flags β€” Message flags. Corresponds to the msg_flags field of a struct msghdr. Unknown flags, if any, are returned in one integer(), last in the containing list πŸ‘€

πŸ§ͺ native_value() = integer() | boolean() | binary()

🎁 cmsg_send() =

cmsg_send() =
    #{level := socket,
      type := timestamp,
      data => native_value(),
      value => timeval()} |
    #{level := socket, type := rights, data := native_value()} |
    #{level := socket,
      type := credentials,
      data := native_value()} |
    #{level := ip,
      type := tos,
      data => native_value(),
      value => ip_tos() | integer()} |
    #{level := ip,
      type := ttl,
      data => native_value(),
      value => integer()} |
    #{level := ip,
      type := hoplimit,
      data => native_value(),
      value => integer()} |
    #{level := ipv6,
      type := tclass,
      data => native_value(),
      value => integer()}

Control messages (ancillary messages) accepted by sendmsg/2,3,4 πŸ’…

A control message may for some message types have a value field with a symbolic value, or a data field with a native value, that has to be binary compatible what is defined in the platform's header files. So like, keep it native, bestie β€” no improvising 🫢

okay so cmsg_recv() is literally the control-message (ancillary message) reveal, bestie β€” these are what you get back from recvmsg/1,2,3,5. A control message has a data field with the native binary value for the message data, and it may also have a decoded value field if this socket library successfully decoded the data for you. no cap, here’s the whole shape of it:

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

       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 := sockaddr_recv()} |
           #{error := posix(),
             origin := icmp,
             type := time_exceeded | 0..255,
             code := 0..255,
             info := 0..4294967295,
             data := 0..4294967295,
             offender := sockaddr_recv()} |
           #{error := posix(),
             origin := icmp6,
             type := dest_unreach,
             code := icmpv6_dest_unreach() | 0..255,
             info := 0..4294967295,
             data := 0..4294967295,
             offender := sockaddr_recv()} |
           #{error := posix(),
             origin := icmp6,
             type := pkt_toobig | time_exceeded | 0..255,
             code := 0..255,
             info := 0..4294967295,
             data := 0..4294967295,
             offender := sockaddr_recv()} |
           #{error := posix(),
             origin := ee_origin() | 0..255,
             type := 0..255,
             code := 0..255,
             info := 0..4294967295,
             data := 0..4294967295,
             offender := sockaddr_recv()}

       posix() = inet:posix()

and posix() is just inet:posix() β€” those POSIX error codes originate from the OS-level socket interface, iykyk. πŸ’…


✨ EXPORTS ✨

🎧 accept β€” answer the call, bestie 🎧

accept(ListenSocket) -> {ok, Socket} | {error, Reason}

accept(ListenSocket, Timeout :: infinity) ->
          {ok, Socket} | {error, Reason}

Types:

  • ListenSocket = Socket = socket()
  • Reason = posix() | closed | invalid()

Accept a connection on a socket, periodt.

This call is used with connection oriented socket types (stream or seqpacket). It returns the first pending incoming connection for a listen socket, or waits for one to arrive, and returns the (newly) connected socket. iconic behavior honestly.

accept(ListenSocket, Timeout :: integer() >= 0) ->
          {ok, Socket} | {error, Reason}

Types:

  • ListenSocket = Socket = socket()
  • Reason = posix() | closed | invalid() | timeout

The same as accept/1 but returns {error, timeout} if no connection has been accepted after Timeout milliseconds. πŸ•°οΈ

Note: bestie be careful β€” if multiple calls are made, only the last call is "valid": {select, {select_info, _Handle}} = socket:accept(LSock, nowait), {error, timeout} = socket:accept(LSock, 500), . . . In the example above, Handle is not valid once the second (accept-) call has been made (the first call is automatically "cancelled" and an abort message sent when the second call is made). After the (accept-) call resulting in the timeout has been made, there is no longer an active accept call! 😭
accept(ListenSocket, Timeout :: nowait) ->
          {ok, Socket} | {select, SelectInfo} | {error, Reason}

accept(ListenSocket, SelectHandle :: select_handle()) ->
          {ok, Socket} | {select, SelectInfo} | {error, Reason}

Types:

  • ListenSocket = Socket = socket()
  • SelectInfo = select_info()
  • Reason = posix() | closed | invalid()

The same as accept/1 but returns promptly β€” no sitting around waiting like a lost little guy. ✨

When there is no pending connection to return, the function will return {select, SelectInfo}, and the caller will later receive a select message, {'$socket', Socket, select, SelectHandle} (with the SelectHandle contained in the SelectInfo) when a client connects. A subsequent call to accept/1,2 will then return the socket. slay.

If the time-out argument is SelectHandle, that term will be contained in a returned SelectInfo and the corresponding select message. The SelectHandle is presumed to be unique to this call.

If the time-out argument is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call.

If the caller doesn't want to wait for a connection, it must immediately call cancel/2 to cancel the operation. don't ghost it, fr fr.

Note: okay so again β€” if multiple calls are made, only the last call is "valid": {select, {select_info, _Handle1}} = socket:accept(LSock, nowait), {select, {select_info, _Handle2}} = socket:accept(LSock, nowait), receive {'$socket', LSock, select, Handle2} -> {ok, ASock} = socket:accept(LSock, nowait), . . . end In the example above, only Handle2 is valid once the second (accept-) call has been made (the first call is automatically "cancelled" and an abort message sent when the second call is made). πŸ’€

πŸͺ’ bind β€” give your socket an address πŸͺ’

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

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. (as they should, honestly)

If you bind a socket to an address in for example the 'inet' or 'inet6' address families, with an ephemeral port number (0), and want to know which port that was chosen, you can find out using something like:

{ok, #{port := Port}} = socket:sockname(Socket)

πŸ›‘ cancel β€” stop the async request, bestie πŸ›‘

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

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.

An ongoing asynchronous operation blocks the socket until the operation has been finished in good order, or until it has been cancelled by this function.

Any other process that tries an operation of the same basic type (accept / send / recv) will be enqueued and notified with the regular select mechanism for asynchronous operations when the current operation and all enqueued before it has been completed.

If SelectInfo does not match an operation in progress for the calling process, this function returns {error, {invalid, SelectInfo}}. not the vibe. πŸ™ˆ

πŸšͺ close β€” say bye to the socket πŸšͺ

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

Types:

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

Closes the socket. bye bestie πŸ‘‹

Note: 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 β€” make the connection happen πŸ“ž

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

connect(Socket, SockAddr, Timeout :: infinity) ->
          ok | {error, Reason}

Types:

  • Socket = socket()
  • SockAddr = sockaddr()
  • Reason = posix() | closed | invalid() | already

This function connects the socket to the address specified by the SockAddr argument, and returns when the connection has been established or failed. main character networking moment. ✨

If a connection attempt is already in progress (by another process), {error, already} is returned.

connect(Socket, SockAddr, Timeout :: integer() >= 0) ->
          ok | {error, Reason}

Types:

  • Socket = socket()
  • SockAddr = sockaddr()
  • Reason = posix() | closed | invalid() | already | timeout

The same as connect/2 but returns {error, timeout} if no connection has been established after Timeout milliseconds. ⏳

Note: when this call has returned {error, timeout} the connection state of the socket is uncertain, since the platform's network stack may complete the connection at any time, up to some platform specific time-out. 😬 Repeating a connection attempt towards the same address would be ok, but towards a different address could end up with a connection to either address. The safe play would be to close the socket and start over. periodt. πŸ’…

Also note that all of this applies when you cancel a connect call using the no-wait time-out described below 😌


connect/3 β€” the "no waiting around" era πŸ’¨

connect(Socket, SockAddr, Timeout :: nowait) ->
          ok | {select, SelectInfo} | {error, Reason}

connect(Socket, SockAddr, SelectHandle :: select_handle()) ->
          ok | {select, SelectInfo} | {error, Reason}

Types:

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

Same as connect/2 but it comes back promptly. Like, it does not sit there and wait, bestie 🫢

If it's not possible to immediately establish a connection, the function returns {select, SelectInfo}, and later the caller gets a select message β€” {'$socket', Socket, select, SelectHandle} (with the SelectHandle that was inside the SelectInfo) β€” when the connection has been completed or has failed. After that, a subsequent call to connect/1 finalizes the connection and hands you the result ✨

If the time-out argument is a SelectHandle, that term gets put inside a returned SelectInfo and the corresponding select message. The SelectHandle is presumed to be unique to this call, so like, don't reuse it πŸ™ˆ

If the time-out argument is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call itself.

If the caller doesn't want to wait for the connection to complete, it must immediately call cancel/2 to cancel the operation. Not later. Immediately. periodt πŸ’…


connect/1 β€” the finalizer πŸŽ€

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

Types:

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

This one finalizes a connection setup on a socket β€” but only after you've called connect(_, _, nowait | select_handle()) and it returned {select, SelectInfo}, and after you've received the select message {'$socket', Socket, select, SelectHandle}. It tells you whether the connection setup was a slay or a flop πŸ”₯

Instead of calling this function, for backwards compatibility, it's allowed to call connect/2,3 β€” but ngl, that incurs more overhead, since the connect address and time-out get processed in vain. Wasteful behaviour, honestly πŸ’€


cancel_monitor/1 β€” bye-bye, monitor πŸ¦‹

cancel_monitor(MRef) -> boolean()

Types:

MRef = reference()

If MRef is a reference that the calling process got by calling monitor/1, this monitor is turned off. If the monitoring is already turned off, nothing happens β€” no drama, no error 🌸

The returned value is one of these:

  • true: The monitor was found and removed. In this case, no 'DOWN' message corresponding to this monitor has been delivered and will not be delivered.
  • false: The monitor was not found and could not be removed. This is probably because a 'DOWN' message corresponding to this monitor has already been placed in the caller's message queue.

Failure: it is an error if MRef refers to a monitor started by another process. Not your monitor, not your business πŸ™…β€β™€οΈ


getopt/2 β€” the otp level πŸ‘‘

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

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

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


getopt/2 β€” the OS protocol levels 🌈

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

Gets a socket option from one of the OS's protocol levels. See the type socket_option() for which options this implementation knows about, how they relate to option names in the OS, and if any of them have known peculiarities πŸ‘€

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. Rude, but true 😭

getopt/3 β€” the backwards-compat one 🫢

getopt(Socket, Level, Opt) -> ok | {error, Reason}

Types:

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

Backwards compatibility function. It's literally the same as getopt(Socket, {Level, Opt}) β€” a little legacy icon doing legacy things πŸ’œ


getopt_native/3 β€” for the options our implementation has never heard of πŸ•΅οΈβ€β™€οΈ

getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level :: level() | (NativeLevel :: integer()),
                   NativeOpt :: integer()},
              ValueType :: integer) ->
                 {ok, Value :: integer()} |
                 {error, posix() | invalid() | closed}

getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level :: level() | (NativeLevel :: integer()),
                   NativeOpt :: integer()},
              ValueType :: boolean) ->
                 {ok, Value :: boolean()} |
                 {error, posix() | invalid() | closed}

getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level :: level() | (NativeLevel :: integer()),
                   NativeOpt :: integer()},
              ValueSize :: integer() >= 0) ->
                 {ok, Value :: binary()} |
                 {error, posix() | invalid() | closed}

getopt_native(X1 :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level :: level() | (NativeLevel :: integer()),
                   NativeOpt :: integer()},
              ValueSpec :: binary()) ->
                 {ok, Value :: binary()} |
                 {error, posix() | invalid() | closed}

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 can be specified either with an ordinary socket_option() tuple, with a known Level = level() and an integer NativeOpt, or with both an integer NativeLevel and NativeOpt.

How to decode the option value has to be specified in one of a few ways: 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 into, 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, have to be deduced from the header files for the running system. Yes, the actual header files. Good luck, bestie πŸ“


i/0 β€” the group photo of all your sockets πŸ“Έ

i() -> ok

Print all sockets in table format in the erlang shell. Iconic. Show-off behaviour πŸ’…


i/1 β€” with info keys πŸ”

i(InfoKeys) -> ok

Types:

InfoKeys = info_keys()

Print all sockets in table format in the erlang shell. What information is included is defined by InfoKeys.


i/1 β€” by domain 🌐

i(Domain) -> ok

Types:

Domain = inet | inet6 | local

Print a selection, based on domain, of the sockets in table format in the erlang shell.


i/1 β€” by protocol πŸ“‘

i(Proto) -> ok

Types:

Proto = sctp | tcp | udp

Print a selection, based on protocol, of the sockets in table format in the erlang shell.


i/1 β€” by type 🧬

i(Type) -> ok

Types:

Type = dgram | seqpacket | stream

Print a selection, based on type, of the sockets in table format in the erlang shell.


i/2 β€” domain + info keys ✨

i(Domain, InfoKeys) -> ok

Types:

Domain = inet | inet6 | local
InfoKeys = info_keys()

Print a selection, based on domain, of the sockets in table format in the erlang shell. What information is included is defined by InfoKeys.


i/2 β€” protocol + info keys 🌸

i(Proto, InfoKeys) -> ok

Types:

Proto = sctp | tcp | udp
InfoKeys = info_keys()

Print a selection, based on domain, of the sockets in table format in the erlang shell. What information is included is defined by InfoKeys. (Yes, it says domain there. That's what the docs say. I'm just the messenger 😭)


i/2 β€” type + info keys πŸ¦‹

i(Type, InfoKeys) -> ok

Types:

Type = dgram | seqpacket | stream
InfoKeys = info_keys()

Print a selection, based on type, of the sockets in table format in the erlang shell. What information is included is defined by InfoKeys.


info/0 β€” the library's whole vibe check πŸ’–

info() -> info()

Get miscellaneous info about the socket library.

The function returns a map with each info item as a key-value binding.

Note: in order to ensure data integrity, mutex'es are taken when needed. So, do not call this function often. It's giving "special occasion only" energy πŸ™ˆ

info/1 β€” this specific socket's vibe check πŸ”₯

info(Socket) -> socket_info()

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 β€” a real-time snapshot, no cap ⭐

Note: in order to ensure data integrity, mutex'es are taken when needed. So, do not call this function often. Same warning, same energy πŸ’€

ioctl/2 β€” get the whole interface list πŸ—‚οΈ

ioctl(Socket, GetRequest) -> {ok, IFConf} | {error, Reason}

Types:

Socket = socket()
GetRequest = gifconf
IFConf = [#{name := string, addr := sockaddr()}]
Reason = posix() | closed

Retrieve socket (device) parameters. Here you get the whole gifconf list, each interface as a map with a name and an addr πŸŽ€


ioctl/3 β€” get one specific device parameter πŸ”§

ioctl(Socket, GetRequest, NameOrIndex) ->
         {ok, Result} | {error, Reason}

Types:

Socket = socket()
GetRequest =
    gifname | gifindex | gifaddr | gifdstaddr | gifbrdaddr |
    gifnetmask | gifhwaddr | gifmtu | giftxqlen | gifflags
NameOrIndex = string() | integer()
Result = term()
Reason = posix() | closed

Retrieve socket (device) parameters. This function retrieves one specific parameter, according to the GetRequest argument. The third argument is the (lookup) "key", identifying the interface β€” usually the name of the interface πŸ‘‘

  • gifname: Get the name of the interface with the specified index (integer()).

Result, the name of the interface, is a string().

  • gifindex β€” gets you the index of the interface with the name you handed in. The result, the interface index, is an integer(). Slay πŸŽ€
  • gifaddr β€” gets you the address of the interface with that name. The result, the address of the interface, is a socket:sockaddr().
  • gifdstaddr β€” gets you the destination address of the point-to-point interface with that name. The result, the destination address of the interface, is a socket:sockaddr().
  • gifbrdaddr β€” gets you the broadcast address for the interface with that name. The result, the broadcast address of the interface, is a socket:sockaddr().
  • gifnetmask β€” gets you the network mask for the interface with that name. The result, the network mask of the interface, is a socket:sockaddr(). Masking era πŸ’…
  • gifhwaddr β€” gets you the hardware address for the interface with that name. The result, the hardware address of the interface, is a socket:sockaddr(). Heads up: the family field contains the 'ARPHRD' device type (or an integer).
  • gifmtu β€” gets you the MTU (Maximum Transfer Unit) for the interface with that name. The result, the MTU of the interface, is an integer().
  • giftxqlen β€” gets you the transmit queue length of the interface with that name. The result, the transmit queue length of the interface, is an integer().
  • gifflags β€” gets you the active flag word of the interface with that name. The result, the active flag word of the interface, is a list of socket:ioctl_device_flag() | integer(). πŸ¦‹

πŸ’œ ioctl(Socket, SetRequest, Name, Value) -> ok | {error, Reason}

Types:

Socket = socket()
SetRequest =
    sifflags | sifaddr | sifdstaddr | sifbrdaddr | sifnetmask
|
    sifhwaddr | gifmtu | siftxqlen
Name = string()
Value = term()
Reason = posix() | closed

Setting socket (device) parameters, bestie. This one sets one specific parameter according to the SetRequest argument. The third argument is the "key" that identifies the interface (usually just the name of the interface), and the fourth is the "new" value.

⚠️ Heads up: these are privileged operations. Like, you need the permissions for this, no cap.
  • sifflags β€” sets the active flag word, #{Flag => boolean()}, of the interface with the specified name.

For every flag you actually want changed, add it to the value map, with the value 'true' if the flag (Flag) should be set and 'false' if the flag should be reset. Very demure, very mindful πŸŽ€

  • sifaddr β€” sets the address, sockaddr(), of the interface with the specified name.
  • sifdstaddr β€” sets the destination address, sockaddr(), of a point-to-point interface with the specified name.
  • sifbrdaddr β€” sets the broadcast address, sockaddr(), of the interface with the specified name.
  • sifnetmask β€” sets the network mask, sockaddr(), of the interface with the specified name.
  • sifmtu β€” sets the MTU (Maximum Transfer Unit), integer(), for the interface with the specified name.
  • siftxqlen β€” sets the transmit queue length, integer(), of the interface with the specified name.

🌈 is_supported(Key1 :: term()) -> boolean()

🌈 is_supported(Key1 :: term(), Key2 :: term()) -> boolean()

This one pulls up info about what your platform actually supports β€” like, is SCTP a thing here, or are certain socket options supported. Vibe check for the whole platform, honestly ✨

For keys other than the known ones, false is returned. And note that in a future version, or on a different platform, there might be more supported items. Platforms grow, okurrr.

This function returns a boolean corresponding to what supports/0-2 reports for the same Key1 (and Key2). Same energy, different function πŸ’…


🫢 listen(Socket) -> ok | {error, Reason}

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

Types:

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

Listen for connections on a socket. That's it, that's the function, and honestly it ate πŸ‘‘


πŸ¦‹ monitor(Socket) -> reference()

Types:

Socket = socket()

Starts monitoring the socket Socket, bestie. We're keeping an eye on it.

If the monitored socket does not exist, or when the monitor is triggered, a 'DOWN' message gets sent that has this pattern:

{'DOWN', MonitorRef, socket, Object, Info}

In the monitor message MonitorRef and Type are the same as described earlier, and:

  • Object β€” the monitored entity, socket, which triggered the event.
  • Info β€” either the termination reason of the socket or nosock (socket Socket did not exist at the time of monitor creation).

Making several calls to socket:monitor/1 for the same Socket is not an error; it results in as many independent monitoring instances. Collect them like little stickers, honestly 🌸


⭐ number_of() -> integer() >= 0

Returns the number of active sockets. Just a count. A little census of your sockets 🧚


πŸ’– open(FD) -> {ok, Socket} | {error, Reason}

πŸ’– open(FD, Opts) -> {ok, Socket} | {error, Reason}

Types:

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

Creates an endpoint (socket) for communication based on an already existing file descriptor. The function attempts to retrieve domain, type and protocol from the system. That is, however, not possible on all platforms, and they should then be specified in Opts. Rude of those platforms, but ok 😭

The Opts argument is intended for providing extra information for the open call:

  • domain β€” which protocol domain the descriptor is of. See also open/2,3,4.
  • type β€” which protocol type type the descriptor is of.

See also open/2,3,4.

  • protocol β€” which protocol the descriptor is of. The atom default is equivalent to the integer protocol number 0, which means the default protocol for a given domain and type.

If the protocol can not be retrieved from the platform for the socket, and protocol is not specified, the default protocol is used, which may or may not be correct. 🫠 (It's giving "trust me bro", so, y'know.)

See also open/2,3,4.

  • dup β€” shall the provided descriptor be duplicated (dup) or not. Defaults to true.
  • debug β€” enable or disable debug during the open call. Defaults to false.
  • use_registry β€” 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 it is necessary to provide domain, type and protocol since they cannot be retrieved from the platform. Not me being dramatic β€” it's literally in the docs πŸ’€

πŸŽ€ open(Domain, Type) -> {ok, Socket} | {error, Reason}

πŸŽ€ open(Domain, Type, Opts) -> {ok, Socket} | {error, Reason}

Types:

Domain = domain() | integer()
Type = type() | integer()
Opts = map()
Socket = socket()
Reason = posix() | protocol

Creates an endpoint (socket) for communication. Iconic behaviour.

The same as open(Domain, Type, default) and open(Domain, Type, default, Opts) respectively. Shortcut szn ✨


πŸ’… open(Domain, Type, Protocol) -> {ok, Socket} | {error, Reason}

πŸ’… open(Domain, Type, Protocol, Opts) -> {ok, Socket} | {error, Reason}

Types:

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

Creates an endpoint (socket) for communication. Main character function, fr fr.

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

Note: For some combinations of Domain and Type the platform has got a default protocol that can be selected with Protocol = default, and the platform may allow or require selecting the default protocol, a specific protocol, or either. So like… read the room (and the platform) before you pick πŸ™ˆ

Examples:

  • socket:open(inet, stream, tcp) β€” it is common that for protocol domain and type inet,stream it is allowed to select the tcp protocol although that mostly is the default.
  • socket:open(local, dgram) β€” it is common that for the protocol domain local it is mandatory to not select a protocol, that is; to select the default protocol.

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.

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

Types:

Socket = socket()
SockAddr = sockaddr_recv()
Reason = posix() | closed

Returns the address of the peer connected to the socket. Who's on the other end? Now you know πŸ‘€


πŸ“ recv(Socket) -> {ok, Data} | {error, Reason} | {error, {Reason, Data}}

πŸ“ recv(Socket, Flags) -> {ok, Data} | {error, Reason} | {error, {Reason, Data}}

okay so we're deep in the recv family now and honestly? this is the part everyone actually cares about β€” getting the data out of the socket 🫢 the vibe is: four flavours of waiting (forever, milliseconds, nowait, or "here's my handle, ping me later"), and then the same four flavours AGAIN for recvfrom, and then recvmsg crashes the party at the very end. slay. let's go πŸ’…


recv β€” the infinite time-out flavour ⏳ (no, it will literally wait forever, that's the whole bit)

recv(Socket, Length) ->
        {ok, Data} | {error, Reason} | {error, {Reason, Data}}

recv(Socket, Flags, Timeout :: infinity) ->
        {ok, Data} | {error, Reason} | {error, {Reason, Data}}

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

recv(Socket, Length, Timeout :: infinity) ->
        {ok, Data} | {error, Reason} | {error, {Reason, Data}}

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

Types:

Socket = socket()
Length = integer() >= 0
Flags = [msg_flag() | integer()]
Data = binary()
Reason = posix() | closed | invalid()

Receives data from a socket, and it will sit there waiting for it to arrive like a loyal bestie at the coffee shop β˜•

  • Length says how many bytes to receive β€” with the iconic special case 0, which means "all available". she's flexible ✨
  • for a socket of type stream, this call will not return until all the requested data can be delivered β€” OR, if you asked for "all available", it returns when the first data chunk arrives πŸŽ€
  • the message Flags can be symbolic msg_flag()s and/or integer()s, exactly like in the platform's appropriate header files. all the values of the symbolic flags and integers get or:ed together (yes, that's a word in this house) πŸ’«
  • when there's a socket error this function returns {error, Reason} β€” or, if some data showed up before the error, {error, {Reason, Data}}. partial slay πŸ™ˆ

recv β€” the millisecond time-out flavour ⏱️

recv(Socket, Flags, Timeout :: integer() >= 0) ->
        {ok, Data} | {error, Reason} | {error, {Reason, Data}}

recv(Socket, Length, Timeout :: integer() >= 0) ->
        {ok, Data} | {error, Reason} | {error, {Reason, Data}}

recv(Socket, Length, Flags, Timeout :: integer() >= 0) ->
        {ok, Data} | {error, Reason} | {error, {Reason, Data}}

Types:

Socket = socket()
Length = integer() >= 0
Flags = [msg_flag() | integer()]
Data = binary()
Reason = posix() | closed | invalid() | timeout

Receives data from a socket, but only waits at most Timeout milliseconds for it to arrive. boundaries, bestie πŸ’…

same as the infinite time-out recv/1,2,3,4, except it returns {error, timeout} β€” or {error, {timeout, Data}} β€” after Timeout milliseconds if the requested data has not been delivered. so you get your answer even if the answer is "nobody's home" 😭


recv β€” the select continuation flavour πŸ¦‹ (aka the "don't block me, I have a life" one)

recv(Socket, Flags, SelectHandle :: nowait) ->
        {ok, Data} |
        {select, SelectInfo} |
        {select, {SelectInfo, Data}} |
        {error, Reason} |
        {error, {Reason, Data}}

recv(Socket, Flags, SelectHandle :: select_handle()) ->
        {ok, Data} |
        {select, SelectInfo} |
        {select, {SelectInfo, Data}} |
        {error, Reason} |
        {error, {Reason, Data}}

recv(Socket, Length, SelectHandle :: nowait) ->
        {ok, Data} |
        {select, SelectInfo} |
        {select, {SelectInfo, Data}} |
        {error, Reason} |
        {error, {Reason, Data}}

recv(Socket, Length, SelectHandle :: select_handle()) ->
        {ok, Data} |
        {select, SelectInfo} |
        {select, {SelectInfo, Data}} |
        {error, Reason} |
        {error, {Reason, Data}}

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

recv(Socket, Length, Flags, SelectHandle :: select_handle()) ->
        {ok, Data} |
        {select, SelectInfo} |
        {select, {SelectInfo, Data}} |
        {error, Reason} |
        {error, {Reason, Data}}

Types:

Socket = socket()
Length = integer() >= 0
Flags = [msg_flag() | integer()]
Data = binary()
SelectInfo = select_info()
Reason = posix() | closed | invalid()

Receives data from a socket, but hands you back a select continuation if the data simply couldn't be returned right away. no ghosting, she leaves a note πŸ’Œ

  • same as the infinite time-out recv/1,2,3,4, BUT if the data cannot be delivered immediately, the function returns {select, SelectInfo}, and you'll then receive a select message β€” {'$socket', Socket, select, SelectHandle} (with the SelectHandle contained in the SelectInfo) β€” when data has arrived. a subsequent call to recv/1,2,3,4 will then return the data πŸ”₯
  • if the time-out argument is SelectHandle, that term will be contained in a returned SelectInfo and in the corresponding select message. the SelectHandle is presumed to be unique to this call πŸ‘‘
  • if the time-out argument is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call ✨
okay so here's the messy one, and I'm quoting it exactly because the manpage really wrote it like this: for a socket of type stream, if Length > 0 and only part of that amount of data is available, the function will return {ok, {Data, SelectInfo with partial data. 😭 that's the literal text, I'm not fixing it, I'm just reporting the news. the part that matters: if the caller doesn't want to wait for more data, it must immediately call cancel/2 to cancel the operation. immediately immediately. periodt 🫢

recvfrom β€” infinite time-out flavour πŸ“¬ (the one that also tells you who sent it)

recvfrom(Socket) -> {ok, {Source, Data}} | {error, Reason}

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

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

recvfrom(Socket, Flags, Timeout :: infinity) ->
            {ok, {Source, Data}} | {error, Reason}

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

recvfrom(Socket, BufSz, Timeout :: infinity) ->
            {ok, {Source, Data}} | {error, Reason}

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

Types:

Socket = socket()
BufSz = integer() >= 0
Flags = [msg_flag() | integer()]
Source = sockaddr_recv()
Data = binary()
Reason = posix() | closed | invalid()

Receive a message from a socket, waiting for it to arrive. yes queen, wait for your message πŸ’œ

  • the function returns when a message is received, or when there's a socket error 🌸
  • BufSz specifies the number of bytes for the receive buffer. if the buffer size is too small, the message will be truncated β€” tragic, do not let that be you πŸ’€
  • if BufSz is not specified or is 0, a default buffer size is used, which can be set by socket:setopt(Socket, {otp,recvbuf}, BufSz) πŸŽ€
  • if it's impossible to know the appropriate buffer size, it may be possible to use the receive message flag peek πŸ‘€ when this flag is used, the message is not "consumed" from the underlying buffers, so another recvfrom/1,2,3,4 call is needed β€” possibly with an adjusted buffer size. look, then grab. iykyk ✨
  • the message Flags may be symbolic msg_flag()s and/or integer()s, as in the platform's appropriate header files, and the values of all symbolic flags and integers are or:ed together πŸ’«

recvfrom β€” millisecond time-out flavour ⏱️

recvfrom(Socket, Flags, Timeout :: integer() >= 0) ->
            {ok, {Source, Data}} | {error, Reason}

recvfrom(Socket, BufSz, Timeout :: integer() >= 0) ->
            {ok, {Source, Data}} | {error, Reason}

recvfrom(Socket, BufSz, Flags, Timeout :: integer() >= 0) ->
            {ok, {Source, Data}} | {error, Reason}

Types:

Socket = socket()
BufSz = integer() >= 0
Flags = [msg_flag() | integer()]
Source = sockaddr_recv()
Data = binary()
Reason = posix() | closed | invalid() | timeout

Receives a message from a socket, waiting at most Timeout milliseconds for it to arrive πŸ•

same as the infinite time-out recvfrom/1,2,3,4, but it returns {error, timeout} after Timeout milliseconds if no message has been delivered. she waited, she's moving on πŸ’…


recvfrom β€” the select continuation flavour πŸ¦‹

recvfrom(Socket, Flags, SelectHandle :: nowait) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}

recvfrom(Socket, Flags, SelectHandle :: select_handle()) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}

recvfrom(Socket, BufSz, SelectHandle :: nowait) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}

recvfrom(Socket, BufSz, SelectHandle :: select_handle()) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}

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

recvfrom(Socket, BufSz, Flags, SelectHandle :: select_handle()) ->
            {ok, {Source, Data}} |
            {select, SelectInfo} |
            {error, Reason}

Types:

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

Receives a message from a socket, but returns a select continuation if no message could be returned immediately πŸŽ€

  • same as the infinite time-out recvfrom/1,2,3,4, but if a message can't be delivered immediately, the function returns {select, SelectInfo}, and the caller will then receive a select message β€” {'$socket', Socket, select, SelectHandle} (with the SelectHandle contained in the SelectInfo) β€” when data has arrived. a subsequent call to recvfrom/1,2,3,4 will then return the message πŸ”₯
  • if the time-out argument is SelectHandle, that term will be contained in a returned SelectInfo and the corresponding select message. the SelectHandle is presumed to be unique to this call πŸ‘‘
  • if the time-out argument is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call ✨
if the caller doesn't want to wait for the data, it must immediately call cancel/2 to cancel the operation. no lingering, no half-finished vibes, just cancel 🫢

recvmsg β€” the fancy multi-part one πŸ‘‘ (clauses first, the Types: list is up next in the following chunk, so hold that thought 🧚)

recvmsg(Socket) -> {ok, Msg} | {error, Reason}

recvmsg(Socket, Flags) -> {ok, Msg} | {error, Reason}

recvmsg(Socket, Timeout :: infinity) ->
           {ok, Msg} | {error, Reason}

recvmsg(Socket, Flags, Timeout :: infinity) ->
           {ok, Msg} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz) -> {ok, Msg} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, Timeout :: infinity) ->
           {ok, Msg} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, Flags, Timeout :: infinity) ->
           {ok, Msg} | {error, Reason}

Types:

(that's where the page hands off β€” the type breakdown for all this lands in the next bit, bestie πŸ’œ)

Type check for the receive side, bestie:

Socket = socket()
BufSz = CtrlSz = integer() >= 0
Flags = [msg_flag() | integer()]
Msg = msg_recv()
Reason = posix() | closed | invalid()

This is the receive a message from a socket and wait for it to arrive situation. The function comes back when a message lands, or when there’s a socket error. BufSz and CtrlSz tell it how many bytes to give the receive buffer and the control message buffer. If the buffer size(s) is(are) too small, the message and/or control message list will be truncated β€” not a slay, just how it is. 😭

If BufSz is not specified or is 0, a default buffer size is used, and you can set that default with socket:setopt(Socket, {otp,recvbuf}, BufSz). Same exact energy for CtrlSz and socket:setopt(Socket, {otp,recvctrlbuf}, CtrlSz). ✨

If it is impossible to know the appropriate buffer size, the receive message flag peek may be your bestie. When peek is used, the message is not β€œconsumed” from the underlying buffers, so another recvfrom/1,2,3,4,5 call is needed β€” possibly with an adjusted buffer size. iykyk. πŸ‘€

The message Flags may be symbolic msg_flag()s and/or integer()s, as in the platform’s appropriate header files. The values of all symbolic flags and integers are or:ed together. πŸ’…


Then we have the recvmsg timeout era:

recvmsg(Socket, Timeout :: integer() >= 0) ->
           {ok, Msg} | {error, Reason}

recvmsg(Socket, Flags, Timeout :: integer() >= 0) ->
           {ok, Msg} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, Timeout :: integer() >= 0) ->
           {ok, Msg} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, Flags,
        Timeout :: integer() >= 0) ->
           {ok, Msg} | {error, Reason}

Types:

Socket = socket()
BufSz = CtrlSz = integer() >= 0
Flags = [msg_flag() | integer()]
Msg = msg_recv()
Reason = posix() | closed | invalid() | timeout

So this receives a message from a socket, waiting at most Timeout milliseconds for it to arrive. It’s the same as recvmsg/1,2,3,4,5 but returns {error, timeout} after Timeout milliseconds if no message has been delivered. ⏰


And the nowait / select-handle era of recvmsg looks like this:

recvmsg(Socket, Timeout :: nowait) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, SelectHandle :: select_handle()) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, Flags, Timeout :: nowait) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, Flags, SelectHandle :: select_handle()) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, SelectHandle :: nowait) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, SelectHandle :: select_handle()) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, Flags, SelectHandle :: nowait) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

recvmsg(Socket, BufSz, CtrlSz, Flags,
        SelectHandle :: select_handle()) ->
           {ok, Msg} | {select, SelectInfo} | {error, Reason}

Types:

Socket = socket()
BufSz = CtrlSz = integer() >= 0
Flags = [msg_flag() | integer()]
Msg = msg_recv()
SelectInfo = select_info()
Reason = posix() | closed | invalid()

This one receives a message from a socket, but returns a select continuation if no message could be returned immediately. πŸ¦‹

It’s the same as the infinite time-out recvfrom/1,2,3,4, but if no message can be delivered immediately, the function returns {select, SelectInfo}, and the caller will then receive a select message, {'$socket', Socket, select, SelectHandle} (with the SelectHandle contained in the SelectInfo) when data has arrived. A subsequent call to recvmsg/1,2,3,4,5 will then return the data. ✨

If the time-out argument is SelectHandle, that term will be contained in a returned SelectInfo and the corresponding select message. The SelectHandle is presumed to be unique to this call. πŸŽ€

If the time-out argument is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call. πŸ‘‘

🚨 If the caller doesn’t want to wait for the data, it must immediately call cancel/2 to cancel the operation. Do not leave it hanging, bestie.

Moving on to send β€” the infinite-timeout squad:

send(Socket, Data) ->
        ok |
        {ok, RestData} |
        {error, Reason} |
        {error, {Reason, RestData}}

send(Socket, Data, Flags) ->
        ok |
        {ok, RestData} |
        {error, Reason} |
        {error, {Reason, RestData}}

send(Socket, Data, Timeout :: infinity) ->
        ok |
        {ok, RestData} |
        {error, Reason} |
        {error, {Reason, RestData}}

send(Socket, Data, Flags, Timeout :: infinity) ->
        ok |
        {ok, RestData} |
        {error, Reason} |
        {error, {Reason, RestData}}

Types:

Socket = socket()
Data = iodata()
Flags = [msg_flag() | integer()]
RestData = binary()
Reason = posix() | closed | invalid()

This sends data on a connected socket, waiting for it to be sent. It will not return until the Data has been accepted by the platform’s network layer, or it reports an error. 🫢

The message Flags may be symbolic msg_flag()s and/or integer()s, matching the platform’s appropriate header files. The values of all symbolic flags and integers are or:ed together. πŸ’…

The Data, if it is not a binary(), is copied into one before calling the platform network API, because a single buffer is required. A returned RestData is a sub binary of this data binary. 🧚

The return value indicates the result from the platform’s network layer:

  • ok: All data has been accepted. βœ…
  • {ok, RestData}: Not all data has been accepted, but no error has been reported. RestData is the tail of Data that has not been accepted.
    • This cannot happen for a socket of type stream where a partially successful send is retried until the data is either accepted or there is an error.
    • For a socket of type dgram this should probably also not happen since a message that cannot be passed atomically should render an error.
    • It is nevertheless possible for the platform’s network layer to return this.
  • {error, Reason}: An error has been reported and no data has been accepted. The posix() Reasons are from the platform’s network layer. closed means that this socket library knows that the socket is closed, and invalid() means that something about an argument is invalid.
    • {error, {Reason, RestData}} : An error has been reported but before that some data was accepted. RestData is the tail of Data that has not been accepted. See {error, Reason} above.
    • This can only happen for a socket of type stream when a partially successful send is retried until there is an error.

Then the send timeout version:

send(Socket, Data, Timeout :: integer() >= 0) ->
        ok |
        {ok, RestData} |
        {error, Reason | timeout} |
        {error, {Reason | timeout, RestData}}

send(Socket, Data, Flags, Timeout :: integer() >= 0) ->
        ok |
        {ok, RestData} |
        {error, Reason | timeout} |
        {error, {Reason | timeout, RestData}}

Types:

Socket = socket()
Data = iodata()
Flags = [msg_flag() | integer()]
RestData = binary()
Reason = posix() | closed | invalid()

This sends data on a connected socket, waiting at most Timeout milliseconds for it to be sent. It’s the same as the infinite time-out send/2,3,4, but returns {error, timeout} or {error, {timeout, RestData}} after Timeout milliseconds if no Data or only some of it was accepted by the platform’s network layer. ⏳


And finally the send nowait / select-handle era:

send(Socket, Data, SelectHandle :: nowait) ->
        ok |
        {ok, RestData} |
        {select, SelectInfo} |
        {select, {SelectInfo, RestData}} |
        {error, Reason}

send(Socket, Data, SelectHandle :: select_handle()) ->
        ok |
        {ok, RestData} |
        {select, SelectInfo} |
        {select, {SelectInfo, RestData}} |
        {error, Reason}

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

send(Socket, Data, Flags, SelectHandle :: select_handle()) ->
        ok |
        {ok, RestData} |
        {select, SelectInfo} |
        {select, {SelectInfo, RestData}} |
        {error, Reason}

Types:

Socket = socket()
Data = iodata()
Flags = [msg_flag() | integer()]
RestData = binary()
SelectInfo = select_info()
Reason = posix() | closed | invalid()

This sends data on a connected socket, but returns a select continuation if the data could not be sent immediately. 🌈

It’s the same as the infinite time-out send/2,3, but if the data is not immediately accepted by the platform network layer, the function returns {select, SelectInfo}, and the caller will then receive a select message, {'$socket', Socket, select, SelectHandle} (with the SelectHandle that was contained in the SelectInfo) when there is room for more data. A subsequent call to send/2-4 will then send the data. ✨

If SelectHandle is a select_handle(), that term will be contained in a returned SelectInfo and the corresponding select message. The SelectHandle is presumed to be unique to this call. πŸŽ€

If SelectHandle is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call. πŸ‘‘

If some of the data was sent, the function will return {ok, {RestData, SelectInfo}, which can only happen for a socket of type stream. If the caller does not want to wait to send the rest of the data, it should immediately cancel the operation with cancel/2. 🚨

πŸ’… send/4 β€” the continuation girlies

send(Socket, Data, Cont) ->
        ok |
        {ok, RestData} |
        {error, Reason} |
        {error, {Reason, RestData}}

send(Socket, Data, Cont, Timeout :: infinity) ->
        ok |
        {ok, RestData} |
        {error, Reason} |
        {error, {Reason, RestData}}

send(Socket, Data, Cont, Timeout :: integer() >= 0) ->
        ok |
        {ok, RestData} |
        {error, Reason | timeout} |
        {error, {Reason | timeout, RestData}}

send(Socket, Data, Cont, SelectHandle :: nowait) ->
        ok |
        {ok, RestData} |
        {select, SelectInfo} |
        {select, {SelectInfo, RestData}} |
        {error, Reason}

send(Socket, Data, Cont, SelectHandle :: select_handle()) ->
        ok |
        {ok, RestData} |
        {select, SelectInfo} |
        {select, {SelectInfo, RestData}} |
        {error, Reason}

Types:

Socket = socket()
Data = iodata()
Cont = select_info()
RestData = binary()
SelectInfo = select_info()
Reason = posix() | closed | invalid()

Okay so this is the pick-up-where-we-left-off version, bestie. It continues sending data on a connected socket when the send operation was already kicked off by send/3,4 and that call handed you back a SelectInfo continuation πŸŽ€. If there's no continuation in play, it behaves like one of these depending on which clause you hit: infinite time-out send/2,3,4, limited time-out send/3,4, or nowait send/3,4 respectively ✨.

Cont is literally the SelectInfo that came back from the previous send() call. No substitutions, no DIY πŸ’….

And yes β€” if Data isn't a binary(), it gets copied into one. Again. 😭 Copying is just what we do here.

The return value tells you what the platform's network layer said. Peep send/2,3,4 and nowait send/3,4 for the full tea πŸ”₯.


πŸ¦‹ sendmsg β€” the whole-message moment

sendmsg(Socket, Msg) ->
           ok |
           {ok, RestData} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Msg, Flags) ->
           ok |
           {ok, RestData} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Msg, Timeout :: infinity) ->
           ok |
           {ok, RestData} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Msg, Flags, Timeout :: infinity) ->
           ok |
           {ok, RestData} |
           {error, Reason} |
           {error, {Reason, RestData}}

Types:

Socket = socket()
Msg = msg_send()
Flags = [msg_flag() | integer()]
RestData = erlang:iovec()
Reason = posix() | closed | invalid()

Sends a whole message on a socket and waits for it to actually go out, no cap 🫢.

The destination β€” if you even need one, i.e. the socket isn't connected β€” lives inside Msg, which also carries the data to send as a list of binaries. And Msg can also hold a list of optional control messages, depending on what your protocol and platform support 🌸.

For a connected socket, there should be no address field in Msg β€” the platform might throw an error at you or just ignore it πŸ™ˆ.

The message data gets handed to the platform's network layer as an I/O vector without copying the content β€” iconic, zero-copy behaviour, we love to see it ✨. But heads up: if the number of elements in the I/O vector is bigger than what the platform allows (that number is reported in the iov_max field from info/0), then on a socket of type stream the send gets iterated over all the elements, but for other socket types the call fails πŸ’€.

This call won't return until the data has been handed over to the platform's network layer, or until it reports an error. Main character energy: it commits ⭐.

The message Flags can be symbolic msg_flag()s and/or integer()s, matching the platform's appropriate header files. All the symbolic flags and integers get OR:ed together into one glorious blob πŸ’œ.

Return value = the result from the platform's network layer. See send/2,3,4 for the lore πŸ‘‘

sendmsg(Socket, Msg, Timeout :: integer() >= 0) ->
           ok |
           {ok, RestData} |
           {error, Reason | timeout} |
           {error, {Reason | timeout, RestData}}

sendmsg(Socket, Msg, Flags, Timeout :: integer() >= 0) ->
           ok |
           {ok, RestData} |
           {error, Reason | timeout} |
           {error, {Reason | timeout, RestData}}

Types:

Socket = socket()
Msg = msg_send()
Flags = [msg_flag() | integer()]
RestData = erlang:iovec()
Reason = posix() | closed | invalid()

Sends a message on a socket but only waits at most Timeout milliseconds for it to be sent, bestie ⏳.

Same as the infinite time-out sendmsg/2,3,4, except it returns {error, timeout} or {error, {timeout, RestData}} after Timeout milliseconds if no data β€” or only some of it β€” got accepted by the platform's network layer. Partial acceptance is real, and she's telling you about it 😭.

sendmsg(Socket, Msg, Timeout :: nowait) ->
           ok |
           {ok, RestData} |
           {select, SelectInfo} |
           {select, {SelectInfo, RestData}} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Msg, SelectHandle :: select_handle()) ->
           ok |
           {ok, RestData} |
           {select, SelectInfo} |
           {select, {SelectInfo, RestData}} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Msg, Flags, SelectHandle :: nowait) ->
           ok |
           {ok, RestData} |
           {select, SelectInfo} |
           {select, {SelectInfo, RestData}} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Msg, Flags, SelectHandle :: select_handle()) ->
           ok |
           {ok, RestData} |
           {select, SelectInfo} |
           {select, {SelectInfo, RestData}} |
           {error, Reason} |
           {error, {Reason, RestData}}

Types:

Socket = socket()
Msg = msg_send()
Flags = [msg_flag() | integer()]
RestData = erlang:iovec()
SelectInfo = select_info()
Reason = posix() | closed | invalid()

Sends a message on a socket, but if the data can't go out immediately she hands you a select continuation instead of making you wait 🧚.

Same as infinity time-out sendmsg/2,3 β€” but if the data isn't immediately accepted by the platform network layer, the function returns {select, SelectInfo}. Then, when there's room for more data, you will receive a select message:

{'$socket', Socket, select, SelectHandle}

…with the SelectHandle that was contained in the SelectInfo. A subsequent call to sendmsg/2-4 will then send the data πŸ”₯.

If SelectHandle is a select_handle(), that term will be contained in a returned SelectInfo and in the corresponding select message. The SelectHandle is presumed to be unique to this call β€” don't be out here reusing handles, that's not the vibe πŸ™ˆ.

If SelectHandle is nowait, and a SelectInfo is returned, it will contain a select_handle() generated by the call. She made it herself, she's proud πŸ’….

And if some of the data was sent, the function returns {ok, {RestData, SelectInfo}, which can only happen for a socket of type stream. If the caller does not want to wait around to send the rest of the data, it should immediately cancel the operation with cancel/2. Like, immediately. Don't leave her hanging 😭.

sendmsg(Socket, Data, Cont) ->
           ok |
           {ok, RestData} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Data, Cont, Timeout :: infinity) ->
           ok |
           {ok, RestData} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Data, Cont, Timeout :: integer() >= 0) ->
           ok |
           {ok, RestData} |
           {error, Reason | timeout} |
           {error, {Reason | timeout, RestData}}

sendmsg(Socket, Data, Cont, SelectHandle :: nowait) ->
           ok |
           {ok, RestData} |
           {select, SelectInfo} |
           {select, {SelectInfo, RestData}} |
           {error, Reason} |
           {error, {Reason, RestData}}

sendmsg(Socket, Data, Cont, SelectHandle :: select_handle()) ->
           ok |
           {ok, RestData} |
           {select, SelectInfo} |
           {select, {SelectInfo, RestData}} |
           {error, Reason} |
           {error, {Reason, RestData}}

Types:

Socket = socket()
Data = msg_send() | erlang:iovec()
Cont = select_info()
RestData = erlang:iovec()
SelectInfo = select_info()
Reason = posix() | closed | invalid()

Continues sending message data on a socket where the send operation was initiated by sendmsg/3,4 that returned a SelectInfo continuation πŸŽ€. Otherwise it behaves like infinite time-out sendmsg/2,3,4, limited time-out sendmsg/3,4, or nowait sendmsg/3,4 respectively β€” pick your fighter ✨.

Cont is the SelectInfo that was returned from the previous sendmsg() call. The one and only πŸ’–.

The return value indicates the result from the platform's network layer. See send/2,3,4 and nowait sendmsg/3,4 πŸ‘‘.


🌈 sendto β€” destination? specified

sendto(Socket, Data, Dest) ->
          ok |
          {ok, RestData} |
          {error, Reason} |
          {error, {Reason, RestData}}

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

sendto(Socket, Data, Dest, Timeout :: infinity) ->
          ok |
          {ok, RestData} |
          {error, Reason} |
          {error, {Reason, RestData}}

sendto(Socket, Data, Dest, Flags, Timeout :: infinity) ->
          ok |
          {ok, RestData} |
          {error, Reason} |
          {error, {Reason, RestData}}

Types:

Socket = socket()
Data = iodata()
Dest = sockaddr()
Flags = [msg_flag() | integer()]
RestData = binary()
Reason = posix() | closed | invalid()

Sends data on a socket to the specified destination and waits for it to be sent, bestie πŸ¦‹. This is the I-know-exactly-where-this-is-going send.

This call will not return until the data has been accepted by the platform's network layer, or until it reports an error. Same commitment issues as before β€” meaning, none πŸ’….

⚠️ Heads up though: if this call is used on a connection mode socket, or on a connected socket, the platform's network layer may return an error or just ignore the destination address. Like, it might straight-up pretend it didn't hear you πŸ™ˆ. No cap.

The Flags in the message can be symbolic msg_flag()s and/or plain integer()s, and they line up with whatever the platform's own header files say. All those symbolic flags and integers get or:ed together β€” like, all of them, one big vibe merge. ✨

The return value tells you what the platform's network layer actually did. Peep send/2,3,4 for the deets.


πŸ• sendto with a Timeout (limited patience era)

sendto(Socket, Data, Dest, Timeout :: integer() >= 0) ->
          ok |
          {ok, RestData} |
          {error, Reason | timeout} |
          {error, {Reason | timeout, RestData}}

sendto(Socket, Data, Dest, Flags, Timeout :: integer() >= 0) ->
          ok |
          {ok, RestData} |
          {error, Reason | timeout} |
          {error, {Reason | timeout, RestData}}

Types, babes:

  • Socket = socket()
  • Data = iodata()
  • Dest = sockaddr()
  • Flags = [msg_flag() | integer()]
  • RestData = binary()
  • Reason = posix() | closed | invalid()

Sends data on a socket, but it'll only wait at most Timeout milliseconds for it to actually get sent. Bestie has a schedule. πŸ’…

It's literally the same as the infinite time-out sendto/3,4,5, except after Timeout milliseconds it hands you {error, timeout} or {error, {timeout, RestData}} if either none of Data or only some of it got accepted by the platform's network layer. Half-sent data is a real thing and she will tell you about it.


πŸ¦‹ sendto nowait / select_handle (the "don't wait up" club)

sendto(Socket, Data, Dest, SelectHandle :: nowait) ->
          ok |
          {ok, RestData} |
          {select, SelectInfo} |
          {select, {SelectInfo, RestData}} |
          {error, Reason}

sendto(Socket, Data, Dest, SelectHandle :: select_handle()) ->
          ok |
          {ok, RestData} |
          {select, SelectInfo} |
          {select, {SelectInfo, RestData}} |
          {error, Reason}

sendto(Socket, Data, Dest, Flags, SelectHandle :: nowait) ->
          ok |
          {ok, RestData} |
          {select, SelectInfo} |
          {select, {SelectInfo, RestData}} |
          {error, Reason}

sendto(Socket, Data, Dest, Flags, SelectHandle :: select_handle()) ->
          ok |
          {ok, RestData} |
          {select, SelectInfo} |
          {select, {SelectInfo, RestData}} |
          {error, Reason}

Types:

  • Socket = socket()
  • Data = iodata()
  • Dest = sockaddr()
  • Flags = [msg_flag() | integer()]
  • RestData = binary()
  • SelectInfo = select_info()
  • Reason = posix() | closed | invalid()

Sends data on a socket, but if it can't go out immediately she hands you a select continuation instead of just standing there awkwardly. Iconic behaviour, honestly. πŸŽ€

Same as the infinity time-out sendto/3,4, except: if the platform's network layer doesn't accept the data right this second, the function returns {select, SelectInfo}, and then you'll get a select message β€” {'$socket', Socket, select, SelectHandle}, with the SelectHandle that was chilling inside the SelectInfo β€” once there's room for more data. Then you just call sendto/3-5 again and it sends the data. No cap. πŸ”₯

If SelectHandle is a select_handle(), that exact term shows up in the returned SelectInfo and in the matching select message. The SelectHandle is presumed to be unique to this call β€” like, one handle, one call, don't share it around, that's messy.

If SelectHandle is nowait and a SelectInfo comes back, it'll contain a select_handle() that the call generated all by itself. Main character energy. πŸ‘‘

If some of the data went out, the function returns {ok, {RestData, SelectInfo} β€” and ngl that can only happen for a socket of type stream. If the caller doesn't want to sit around waiting to send the rest, it should immediately cancel the operation with cancel/2. Don't leave her hanging. πŸ™ˆ


🌸 Continuing a sendto (the Cont glow-up)

sendto(Socket, Data, Cont) ->
          ok |
          {ok, RestData} |
          {error, Reason} |
          {error, {Reason, RestData}}

sendto(Socket, Data, Cont, Timeout :: infinity) ->
          ok |
          {ok, RestData} |
          {error, Reason} |
          {error, {Reason, RestData}}

sendto(Socket, Data, Cont, Timeout :: integer() >= 0) ->
          ok |
          {ok, RestData} |
          {error, Reason | timeout} |
          {error, {Reason | timeout, RestData}}

sendto(Socket, Data, Cont, SelectHandle :: nowait) ->
          ok |
          {ok, RestData} |
          {select, SelectInfo} |
          {select, {SelectInfo, RestData}} |
          {error, Reason}

sendto(Socket, Data, Cont, SelectHandle :: select_handle()) ->
          ok |
          {ok, RestData} |
          {select, SelectInfo} |
          {select, {SelectInfo, RestData}} |
          {error, Reason}

Types:

  • Socket = socket()
  • Data = iodata()
  • Cont = select_info()
  • RestData = binary()
  • SelectInfo = select_info()
  • Reason = posix() | closed | invalid()

Continues sending data on a socket where the send was already kicked off by sendto/4,5 that returned a SelectInfo continuation. Otherwise it's exactly like the infinity time-out sendto/3,4,5, the limited time-out sendto/4,5, or the nowait sendto/4,5, respectively. Pick your fighter. ⭐

Cont is the SelectInfo that came back from the previous sendto() call β€” she's the receipt, keep her safe.

If Data isn't a binary(), it gets copied into one. Again. Yes, again. 😭

The return value shows what the platform's network layer did. See send/2,3,4 and nowait sendto/4,5.


🧚 sendfile with an infinity time-out (the patient queen)

sendfile(Socket, FileHandle, Offset, Count, Timeout :: infinity) ->
            {ok, BytesSent} |
            {error, Reason} |
            {error, {Reason, BytesSent}}

Types:

  • Socket = socket()
  • FileHandle = file:fd()
  • Offset = integer()
  • Count = BytesSent = integer() >= 0
  • Reason = posix() | closed | invalid()

Sends file data on a socket to the specified destination, waiting for it to be sent (that's the "infinite" time-out β€” she will wait forever, lowkey devoted).

The FileHandle must refer to an open raw file as described in file:open/2. Like, raw raw. Don't show up with anything else.

This call will not return until the data has been accepted by the platform's network layer, or it reports an error. Periodt.

The Offset argument is the file offset to start reading from. Default value is 0.

The Count argument is the number of bytes to transfer from FileHandle to Socket. If Count =:= 0 (the default), the transfer stops at the end of file. Very "we'll know when we get there" of her.

The return value tells you what the platform's network layer did:

  • {ok, BytesSent} β€” the transfer completed successfully after BytesSent bytes of data. Slay. πŸ’–
  • {error, Reason} β€” an error got reported and no data was transferred. The posix() Reasons come from the platform's network layer. closed means this socket library knows the socket is closed, and invalid() means something about an argument is invalid.
    • {error, {Reason, BytesSent}} β€” an error got reported, but before that, some data did get transferred. See {error, Reason} and {ok, BytesSent} above.

⏳ sendfile with a real Timeout (limited patience, again)

sendfile(Socket, FileHandle, Offset, Count,
         Timeout :: integer() >= 0) ->
            {ok, BytesSent} |
            {error, Reason | timeout} |
            {error, {Reason | timeout, BytesSent}}

Types:

  • Socket = socket()
  • FileHandle = file:fd()
  • Offset = integer()
  • Count = BytesSent = integer() >= 0
  • Reason = posix() | closed | invalid()

Sends file data on a socket, waiting at most Timeout milliseconds for it to be sent (limited time-out).

Same as the "infinite" time-out sendfile/5, but it returns {error, timeout} or {error, {timeout, BytesSent}} after Timeout milliseconds if not all the file data was transferred by the platform's network layer. She tried, bestie. 🫢


πŸ¦‹ sendfile nowait / select_handle (no waiting, no drama)

sendfile(Socket, FileHandle, Offset, Count,
         SelectHandle :: nowait) ->
            {ok, BytesSent} |
            {select, SelectInfo} |
            {select, {SelectInfo, BytesSent}} |
            {error, Reason}

sendfile(Socket, FileHandle, Offset, Count,
         SelectHandle :: select_handle()) ->
            {ok, BytesSent} |
            {select, SelectInfo} |
            {select, {SelectInfo, BytesSent}} |
            {error, Reason}

Types:

  • Socket = socket()
  • FileHandle = file:fd()
  • Offset = integer()
  • Count = BytesSent = integer() >= 0
  • SelectInfo = select_info()
  • Reason = posix() | closed | invalid()

Sends file data on a socket, but returns a select continuation if the data couldn't be sent immediately (nowait).

Same as the "infinite" time-out sendfile/5, except if the data isn't immediately accepted by the platform's network layer, the function returns {select, SelectInfo}, and then you'll get a select message β€” {'$socket', Socket, select, SelectHandle}, with the SelectHandle that lived inside the SelectInfo β€” once there's room for more data. Then calling sendfile/3 with SelectInfo as the second argument continues the data transfer. We love a comeback. 🌈

If SelectHandle is a select_handle(), that term will be in the returned SelectInfo and in the matching select message. The SelectHandle is presumed to be unique to this call.

If SelectHandle is nowait and a SelectInfo comes back, it'll contain a select_handle() generated by the call.

If some file data was sent, the function returns {ok, {BytesSent, SelectInfo}. If the caller doesn't want to wait to send the rest of the data, it should immediately cancel the operation with cancel/2. Bestie, don't ghost her β€” cancel properly. πŸ’€


πŸ’œ Continuing a sendfile (the Cont sequel)

sendfile(Socket, Cont, Offset, Count, Timeout :: infinity) ->
            {ok, BytesSent} |
            {error, Reason} |
            {error, {Reason, BytesSent}}

sendfile(Socket, Cont, Offset, Count,
         Timeout :: integer() >= 0) ->
            {ok, BytesSent} |
            {error, Reason | timeout} |
            {error, {Reason | timeout, BytesSent}}

sendfile(Socket, Cont, Offset, Count, SelectHandle :: nowait) ->
            {ok, BytesSent} |
            {select, SelectInfo} |
            {select, {SelectInfo, BytesSent}} |
            {error, Reason}

sendfile(Socket, Cont, Offset, Count,
         SelectHandle :: select_handle()) ->
            {ok, BytesSent} |
            {select, SelectInfo} |
            {select, {SelectInfo, BytesSent}} |
            {error, Reason}

Same energy as the sendto continuation club β€” the Cont comes straight out of the SelectInfo that the previous sendfile handed back, and she picks the transfer right back up where it left off. ✨

...and the continuation clause of sendfile/5 β€” the one where you hand back a SelectInfo you got earlier β€” takes these types:

Socket = socket()
Cont = select_info()
Offset = integer()
Count = BytesSent = integer() >= 0
SelectInfo = select_info()
Reason = posix() | closed | invalid()

So what it actually does: it keeps sending file data on a socket when the send op was started by sendfile/3,5 and that call handed you back a SelectInfo continuation. ✨ In every other way it behaves just like "infinite" time-out sendfile/5, limited time-out sendfile/5, or nowait sendfile/5 β€” depending on which flavour you're continuing, iykyk.

Cont is literally the SelectInfo that the previous sendfile() call gave you. 🫢

The return value tells you what the platform's network layer did β€” same as the "infinite" time-out sendfile/5. No cap.


πŸ¦‹ sendfile(Socket, FileHandle, Offset, Count) -> Result

Types:

Socket = socket()
FileHandle = file:fd()
Offset = integer()
Count = integer() >= 0

Same energy as sendfile(Socket, FileHandle, Offset, Count, infinity) β€” send the file data at Offset and Count to the socket, and there's no time-out other than whatever the platform's network stack decides. πŸ’…


πŸ¦‹ sendfile(Socket, FileHandle, Timeout) -> Result

Types:

Socket = socket()
FileHandle = file:fd()
 Timeout = timeout() | 'nowait' | select_handle()

Depends on what you pass as Timeout, bestie β€” it's one of: sendfile(Socket, FileHandle, 0, 0, infinity), sendfile(Socket, FileHandle, 0, 0, Timeout), or sendfile(Socket, FileHandle, 0, 0, SelectHandle). Basically: send all the data in the file to the socket, with the Timeout you asked for. πŸŽ€


πŸ¦‹ sendfile(Socket, FileHandle) -> Result

Types:

Socket = socket()
FileHandle = file:fd()

Same as sendfile(Socket, FileHandle, 0, 0, infinity) β€” send all the data in the file to the socket, no time-out other than from the platform's network stack. The lazy-girl option and honestly? iconic. πŸ‘‘


⭐ setopt/3 at the otp level

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

Sets a socket option in the protocol level otp β€” which is this implementation's level sitting above the OS protocol layers. 🌈 Peep the type otp_socket_option() for what's available up here.


⭐ setopt/3 for OS protocol levels

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

Sets a socket option in one of the OS's protocol levels. Check the type socket_option() for which options this implementation actually knows about, how they map to option names in the OS, and whether any of them have known peculiarities. πŸ™ˆ

Which options are valid depends on what kind of socket it is β€” domain(), type() and protocol().

More info lives in the socket options chapter of the users guide. go read it, it's giving homework but make it cute.

Note: Not all options are valid, nor possible to set, on all platforms. So like β€” even if we support an option, that does NOT mean the underlying OS does. πŸ’€ vibe check your platform first.

πŸ’œ setopt(Socket, Level, Opt, Value) -> ok | {error, Reason}

Types:

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

Backwards compatibility function, aww. πŸŽ€

Literally the same as setopt(Socket, {Level, Opt}, Value).


🧚 setopt_native/3 β€” for the brave

setopt_native(Socket :: socket(),
              SocketOption ::
                  socket_option() |
                  {Level :: level() | (NativeLevel :: integer()),
                   NativeOpt :: integer()},
              Value :: native_value()) ->
                 ok | {error, posix() | invalid() | closed}

Sets a socket option that might be completely unknown to our implementation, or whose type just doesn't vibe with our implementation β€” that is, in "native mode". 😭

How Value gets used:

  • If Value is an integer() it'll be used as a C type (int).
  • If it's a boolean() it's used as a C type (int) with the C implementation's values for false or true.
  • If it's a binary() then its content and size are used as the option value.

The socket option can be specified with an ordinary socket_option() tuple, with a known Level = level() plus an integer NativeOpt, or with both an integer NativeLevel and NativeOpt. πŸ¦‹

Which options are valid depends on the socket kind β€” domain(), type() and protocol().

The integer values for NativeLevel and NativeOpt, plus how Value is encoded, has to be deduced from the header files for the running system. That's on you, bestie. πŸ”₯


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

Types:

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

Shuts down all or part of a full-duplex connection. read, write, or read_write β€” pick your fighter. ✨


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

Types:

Socket = socket()
SockAddr = sockaddr_recv()
Reason = posix() | closed

Returns the current address the socket is bound to. πŸ’–


πŸ‘‘ supports/0, supports/1, supports/2

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

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

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

These functions retrieve info about what the platform supports β€” like which platform features, or which socket options, are supported. πŸ”

For keys other than the known ones, the empty list gets returned. Also note: 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, plus {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))
    • sendfile β€” Sendfile support (sendfile(2))
  • supports(msg_flags = Key1) β€” returns a list of {Flag, boolean()} tuples for every Flag in msg_flag(), with the boolean() saying whether that flag is supported on this platform. 🏳️
  • supports(protocols = Key1) β€” returns a list of {Name :: atom(), boolean()} tuples for every Name in protocol(), the boolean() saying whether the protocol is supported on this platform.
  • supports(options = Key1) β€” returns a list of {SocketOption, boolean()} tuples for every SocketOption in socket_option(), the boolean() saying whether the socket option is supported on this platform.
    • supports(options = Key1, Key2) β€” for a Key2 in level(), returns a list of {Opt, boolean()} tuples for all known socket options Opt where Level =:= Key2, with the boolean() saying whether the socket option is supported on this platform. See setopt/3 and getopt/2. πŸ’…

πŸŽ€ use_registry(D :: boolean()) -> ok

Globally flips whether the socket registry is used or not. But heads up β€” you can still override this explicitly when creating an individual socket, see open/2 or open/4 for more info (use the Extra argument). 🫢


πŸ¦‹ which_sockets/0 and which_sockets/1

which_sockets() -> [socket()]

which_sockets(FilterRule) -> [socket()]

Types:

FilterRule =
    inet | inet6 | local | stream | dgram | seqpacket | sctp |
    tcp | udp |
    pid() |
    fun((socket_info()) -> boolean())

Returns a list of all the sockets that match the filter rule. 🌈

There are several pre-made filter rules and one general one:

  • 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 based on which sockets have this pid as their 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 could be included, false if it should not). ✨

🌟 EXAMPLES 🌟

okay bestie, here's the whole thing end-to-end, ate and left no crumbs:

client(SAddr, SPort) ->
   {ok, Sock} = socket:open(inet, stream, tcp),
   ok = socket:connect(Sock, #{family => inet,
                               addr   => SAddr,
                               port   => SPort}),
   Msg = <<"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:close(Sock),
   ok = socket:close(LSock).

and that's a wrap on socket(3erl), besties 🫢✨ this page is from Ericsson AB, and it ships with kernel 8.5.4.2, dated at the bottom of the original page. go build something unhinged with it, ily, bye πŸ’…πŸ’–

πŸ“¦ where this page comes from