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 theTimeoutargument tonowait. So for example, if you call therecv/3function withTimeoutset tonowait(recv(Sock, 0, nowait)) and there's actually nothing to read, it'll come back with{select, SelectInfo}(andSelectInfocontains theSelectHandle). 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_SOCKETwith options namedSO_*.ipβIPPROTO_IPa.k.aSOL_IPwith options namedIP_*.ipv6βIPPROTO_IPV6a.k.aSOL_IPV6with options namedIPV6_*.tcpβIPPROTO_TCPwith options namedTCP_*.udpβIPPROTO_UDPwith options namedUDP_*.sctpβIPPROTO_SCTPwith options namedSCTP_*.
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 valuedefaultis only valid to set.Nspecifies 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 valuedefaultis only valid to set. πsndctrlbuf:βBufSize :: (default | integer()>0)β buffer size for sent ancillary messages. The valuedefaultis only valid to set. πfd:βinteger()β only valid to get. The OS protocol levels' socket descriptor. Functionsopen/1,2can 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 withopen/2oropen/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
abortis shorthand for#{onoff => true, linger => 0}, and only valid to set.
- The value
{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-4withpeekinFlags. π don't do it.
- Currently disabled due to a possible infinite loop when calling
{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-rcvsndtimeoconfigure 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
Timeoutargument to, for instance, therecv/3function.
- This option is unsupported per default; OTP has to be explicitly built with the
{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-rcvsndtimeoconfigure 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
Timeoutargument to, for instance, thesend/3function.
- This option is unsupported per default; OTP has to be explicitly built with the
{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
nullpasses aNULLpointer and size0to 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.
- An
{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 flagerrqueue, and usingrecvmsg/1,2,3,4,5to get all error information in the message'sctrlfield as a control message#{level := ip, type := recverr}. π¨
A working strategy should be to first poll the error queue usingrecvmsg/2,3,4withTimeout =:= 0andFlagscontainingerrqueue(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 thenowait | select_handle()recv functions:recv/3,4,recvfrom/3,4orrecvmsg/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()β π aninteger()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 isinet, 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()β aninteger()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()}
π§ sctp_assocparams() = #{assoc_id := integer(), asocmaxrxt := 0..65535, numbe_peer_destinations := 0..65535, peer_rwnd := 0..4294967295, local_rwnd := 0..4294967295, cookie_life := 0..4294967295}
Corresponds to the C struct sctp_assocparams. (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 tomsg_nameandmsg_namelenfields of a structmsghdr. If not used they are set toNULL,0.iovβ Mandatory data as a list of binaries. Themsg_iovandmsg_iovlenfields of a structmsghdr.ctrlβ Optional list of control messages (CMSG). Corresponds to themsg_controlandmsg_controllenfields of a structmsghdr. If not used they are set toNULL,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 tomsg_nameandmsg_namelenfields of a structmsghdr. IfNULLthe map key is not present.iovβ Data as a list of binaries. Themsg_iovandmsg_iovlenfields of a structmsghdr.ctrlβ A possibly empty list of control messages (CMSG). Corresponds to themsg_controlandmsg_controllenfields of a structmsghdr.flagsβ Message flags. Corresponds to themsg_flagsfield of a structmsghdr. Unknown flags, if any, are returned in oneinteger(), 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,Handleis 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), . . . endIn the example above, onlyHandle2is 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 | loopbackReason = 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 aninteger(). Slay πgifaddrβ gets you the address of the interface with that name. The result, the address of the interface, is asocket: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 asocket:sockaddr().gifbrdaddrβ gets you the broadcast address for the interface with that name. The result, the broadcast address of the interface, is asocket:sockaddr().gifnetmaskβ gets you the network mask for the interface with that name. The result, the network mask of the interface, is asocket:sockaddr(). Masking era πgifhwaddrβ gets you the hardware address for the interface with that name. The result, the hardware address of the interface, is asocket:sockaddr(). Heads up: thefamilyfield 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 aninteger().giftxqlenβ gets you the transmit queue length of the interface with that name. The result, the transmit queue length of the interface, is aninteger().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 ofsocket: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 ornosock(socketSocketdid 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 alsoopen/2,3,4.typeβ which protocol typetypethe descriptor is of.
See also open/2,3,4.
protocolβ which protocol the descriptor is of. The atomdefaultis equivalent to the integer protocol number0, 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 totrue.debugβ enable or disable debug during theopencall. Defaults tofalse.use_registryβ enable or disable use of the socket registry for this socket. This overrides the global value. Defaults to the global value, seeuse_registry/1.
Note: This function should be used with care! On some platforms it is necessary to providedomain,typeandprotocolsince 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 ofDomainandTypethe platform has got a default protocol that can be selected withProtocol = 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 typeinet,streamit is allowed to select thetcpprotocol although that mostly is the default.socket:open(local, dgram)β it is common that for the protocol domainlocalit 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 theopencall. Only supported on the Linux platform. π§debug:boolean()β enable or disable debug during theopencall. Defaults tofalse.use_registry:boolean()β enable or disable use of the socket registry for this socket. This overrides the global value. Defaults to the global value, seeuse_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 β
Lengthsays how many bytes to receive β with the iconic special case0, 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
Flagscan be symbolicmsg_flag()s and/orinteger()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 theSelectHandlecontained in theSelectInfo) β when data has arrived. a subsequent call torecv/1,2,3,4will then return the data π₯ - if the time-out argument is
SelectHandle, that term will be contained in a returnedSelectInfoand in the corresponding select message. theSelectHandleis presumed to be unique to this call π - if the time-out argument is
nowait, and aSelectInfois returned, it will contain aselect_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 typestream, ifLength > 0and 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 callcancel/2to 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 πΈ
BufSzspecifies 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
BufSzis not specified or is0, a default buffer size is used, which can be set bysocket: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 anotherrecvfrom/1,2,3,4call is needed β possibly with an adjusted buffer size. look, then grab. iykyk β¨ - the message
Flagsmay be symbolicmsg_flag()s and/orinteger()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 theSelectHandlecontained in theSelectInfo) β when data has arrived. a subsequent call torecvfrom/1,2,3,4will then return the message π₯ - if the time-out argument is
SelectHandle, that term will be contained in a returnedSelectInfoand the corresponding select message. theSelectHandleis presumed to be unique to this call π - if the time-out argument is
nowait, and aSelectInfois returned, it will contain aselect_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.RestDatais the tail ofDatathat has not been accepted.- This cannot happen for a socket of type
streamwhere a partially successful send is retried until the data is either accepted or there is an error. - For a socket of type
dgramthis 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.
- This cannot happen for a socket of type
{error, Reason}: An error has been reported and no data has been accepted. Theposix()Reasons are from the platformβs network layer.closedmeans that this socket library knows that the socket is closed, andinvalid()means that something about an argument is invalid.{error, {Reason, RestData}}: An error has been reported but before that some data was accepted.RestDatais the tail ofDatathat has not been accepted. See{error, Reason}above.- This can only happen for a socket of type
streamwhen 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() >= 0Reason = 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 afterBytesSentbytes of data. Slay. π{error, Reason}β an error got reported and no data was transferred. Theposix()Reasons come from the platform's network layer.closedmeans this socket library knows the socket is closed, andinvalid()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() >= 0Reason = 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() >= 0SelectInfo = 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
Valueis aninteger()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 everyKey1described insupports/1, plus{Key1, boolean()}tuples for each of the following keys:sctpβ SCTP supportipv6β IPv6 supportlocalβ 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 everyFlaginmsg_flag(), with theboolean()saying whether that flag is supported on this platform. π³οΈsupports(protocols = Key1)β returns a list of{Name :: atom(), boolean()}tuples for everyNameinprotocol(), theboolean()saying whether the protocol is supported on this platform.supports(options = Key1)β returns a list of{SocketOption, boolean()}tuples for everySocketOptioninsocket_option(), theboolean()saying whether the socket option is supported on this platform.supports(options = Key1, Key2)β for aKey2inlevel(), returns a list of{Opt, boolean()}tuples for all known socket optionsOptwhereLevel =:= Key2, with theboolean()saying whether the socket option is supported on this platform. Seesetopt/3andgetopt/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 aboolean()(trueif the socket could be included,falseif 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
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms