UDP and inet

In Erlang a UDP socket has no connection: one send is one datagram, and one receive is one datagram with the address of whoever sent it. Nothing retransmits a loss, nothing tells the sender that the receiver was gone, and nothing keeps an order between two datagrams. That sounds like a worse protocol, and it is a different tool: a metric, a discovery broadcast or a heartbeat is worth sending even if some of them never arrive, and a datagram that arrives is cheap. This lesson is the TCP lesson without the connection.

A datagram

gen_udp:open(Port, Options) binds a socket; gen_udp:send(Socket, Address, Port, Data) sends one datagram, and gen_udp:recv(Socket, Length, Timeout) waits for one. The address is a tuple of four numbers for IPv4, and the receiving call answers the address and the port of the sender as well as the data, because a UDP socket has no idea who will talk to it next:

udp_echo.erl

-module(udp_echo). -export([main/0]). main() -> {ok, Receiver} = gen_udp:open(0, [binary, {active, false}]), {ok, Port} = inet:port(Receiver), {ok, Sender} = gen_udp:open(0, [binary]), ok = gen_udp:send(Sender, {127, 0, 0, 1}, Port, <<"ping">>), {ok, {Address, _SenderPort, Packet}} = gen_udp:recv(Receiver, 0, 1000), io:format("from: ~s~n", [inet:ntoa(Address)]), io:format("packet: ~p~n", [Packet]), ok = gen_udp:close(Sender), ok = gen_udp:close(Receiver).

erlc udp_echo.erl

erl -noshell -eval 'udp_echo:main(), halt().'

from: 127.0.0.1 packet: <<"ping">>

Port zero asks for a free port, the same way it does for TCP, and inet:port/1 reads it back. The sender keeps no state about the receiver: the address and the port travel with every call, so one socket can talk to a hundred receivers without a hundred connections. inet:ntoa/1 turns the four numbers into the text form a human reads.

Active UDP

The passive mode blocks in recv, which is fine for a test and wrong for a server that must also answer its own messages. In an active mode the datagram arrives as {udp, Socket, Address, Port, Data} in the mailbox of the owner. {active, once} asks for one at a time and is the safe default; {active, true} asks for everything, which is a flood waiting to happen:

udp_active.erl

-module(udp_active). -export([main/0]). main() -> {ok, Receiver} = gen_udp:open(0, [binary, {active, true}]), {ok, Port} = inet:port(Receiver), {ok, Sender} = gen_udp:open(0, [binary]), ok = gen_udp:send(Sender, {127, 0, 0, 1}, Port, <<"first">>), ok = gen_udp:send(Sender, {127, 0, 0, 1}, Port, <<"second">>), receive {udp, Receiver, Address, _Port, Data} -> io:format("first: ~p from ~s~n", [Data, inet:ntoa(Address)]) after 1000 -> io:format("nothing arrived~n") end, receive {udp, Receiver, _Address, _Port2, Data2} -> io:format("second: ~p~n", [Data2]) after 1000 -> io:format("nothing arrived~n") end, ok = gen_udp:close(Sender), ok = gen_udp:close(Receiver).

erlc udp_active.erl

erl -noshell -eval 'udp_active:main(), halt().'

first: <<"first">> from 127.0.0.1 second: <<"second">>

Each datagram arrives whole and on its own: no framing, no packet mode, and no relation between two messages. The order of two datagrams on loopback is the order they were sent, and on a real network it is not: a router may send the second one first, and a receiver that depends on the order needs a sequence number in the payload, or TCP.

Addresses

The inet module is the one that turns names and strings into the tuples the sockets want. inet:getaddr/2 resolves a name, inet:parse_address/1 reads the text form without a DNS lookup, inet:ntoa/1 goes back to text, and a bad address is an error tuple rather than an exception:

names.erl

-module(names). -export([main/0]). main() -> io:format("localhost: ~p~n", [inet:getaddr("localhost", inet)]), io:format("parsed: ~p~n", [inet:parse_address("127.0.0.1")]), io:format("bad address: ~p~n", [inet:parse_address("127.0.0.300")]), io:format("text: ~s~n", [inet:ntoa({127, 0, 0, 1})]).

erlc names.erl

erl -noshell -eval 'names:main(), halt().'

localhost: {ok,{127,0,0,1}} parsed: {ok,{127,0,0,1}} bad address: {error,einval} text: 127.0.0.1

A server binds to {0,0,0,0} to listen on every interface and to {127,0,0,1} to stay on the loopback, and the address a client may use is the one the other machine sees. That is why a service behind a NAT needs its external address in the configuration and not the one the interface reports.

A datagram that is lost

The mistake a reader makes with UDP is to treat ok from send as delivery. It means the local socket passed the datagram to the network, and nothing more. This program opens a receiver, closes it, and sends to the port it used to hold: the send still answers ok, and the receive waits out its timeout:

closed_port.erl

-module(closed_port). -export([main/0]). main() -> {ok, Receiver} = gen_udp:open(0, [binary, {active, false}]), {ok, Port} = inet:port(Receiver), ok = gen_udp:close(Receiver), {ok, Sender} = gen_udp:open(0, [binary, {active, false}]), ok = gen_udp:send(Sender, {127, 0, 0, 1}, Port, <<"gone">>), io:format("recv: ~p~n", [gen_udp:recv(Sender, 0, 100)]), io:format("send again: ~p~n", [gen_udp:send(Sender, {127, 0, 0, 1}, Port, <<"gone">>)]), ok = gen_udp:close(Sender).

erlc closed_port.erl

erl -noshell -eval 'closed_port:main(), halt().'

recv: {error,timeout} send again: ok

Two answers, both cheerful, and the datagram never arrived. A protocol on UDP builds its own guarantees: a sequence number to notice a gap, an acknowledgement when the receiver must know, a repeated send for something important, and a limit on the payload so that one datagram fits the path. The capstone TCP server is the same job over a connection that does all of that for it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does one gen_udp:recv/3 answer?

    Answer

    One whole datagram with the sender address and port

    A datagram arrives whole, and the address travels with it because the socket has no connection.

  2. What does ok from gen_udp:send/4 mean?

    Answer

    The local socket passed it to the network

    UDP has no acknowledgement, so the call can only report what the local side did.

  3. Which message carries a datagram in an active mode?

    Answer

    {udp, Socket, Address, Port, Data}

    The message names the socket and both parts of the sender address as well as the data.

  4. What does inet:parse_address/1 do with a bad address?

    Answer

    Answers {error, einval}

    The text is read without a lookup, and a wrong one is a normal error tuple.

  5. Why can two datagrams arrive in a different order than they were sent?

    Answer

    They travel independently and no layer reorders them

    Without a connection and retransmission there is nothing that keeps the order of two datagrams.

  6. What does a UDP receiver see when the datagram is lost?

    Answer

    Nothing at all

    The loss has no message; a receive simply times out, and a protocol that needs to know adds its own check.

  7. What does this module print? -module(q1). -export([main/0]). main() -> {ok, R} = gen_udp:open(0, [binary, {active, false}]), {ok, Port} = inet:port(R), {ok, S} = gen_udp:open(0, [binary]), ok = gen_udp:send(S, {127, 0, 0, 1}, Port, <<"abc">>), {ok, {_Address, _From, Packet}} = gen_udp:recv(R, 0, 1000), io:format("~p~n", [Packet]).

    Answer

    <<"abc">>

    The binary option keeps the payload as the binary that was sent, whole.

  8. What does this module print? -module(q2). -export([main/0]). main() -> io:format("~p~n", [inet:parse_address("10.0.0.1")]).

    Answer

    {ok,{10,0,0,1}}

    The text form parses to a four number tuple inside an ok tuple.

  9. What does this module print? -module(q3). -export([main/0]). main() -> {ok, R} = gen_udp:open(0, [binary, {active, true}]), {ok, Port} = inet:port(R), {ok, S} = gen_udp:open(0, [binary]), ok = gen_udp:send(S, {127, 0, 0, 1}, Port, <<"m">>), receive {udp, R, _Address, _From, Data} -> io:format("~p~n", [Data]) after 1000 -> io:format("nothing~n") end.

    Answer

    <<"m">>

    The active mode delivers the datagram as a message to the owner, which is the process that opened the socket.

  10. What does this module print? -module(q4). -export([main/0]). main() -> {ok, R} = gen_udp:open(0, [binary, {active, false}]), {ok, Port} = inet:port(R), ok = gen_udp:close(R), {ok, S} = gen_udp:open(0, [binary, {active, false}]), io:format("~p~n", [gen_udp:send(S, {127, 0, 0, 1}, Port, <<"x">>)]).

    Answer

    ok

    Nothing on the local side can know that the port is closed, so the send reports success.

The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Автор статьи: Arthur Isaev

Изображение баннера