STUN client
Overview
The sample asks a STUN server (RFC 8489) which address it sees the device
at, and prints the answer: the public address of the device, the one it has on
the outside of the NAT of its network. One call does it,
stun_client_simple().
See STUN for the library, and for what an application does to learn the address of a socket of its own.
Requirements
A network through which the STUN server can be reached. The device takes its address and its DNS servers from DHCP.
A STUN server. The default is a public one;
CONFIG_NET_SAMPLE_STUN_SERVERandCONFIG_NET_SAMPLE_STUN_SERVER_PORTname another. The address that is printed is the public one only if the server is on the other side of the NAT: a server in the local network sees the local address.An entropy source: the transaction id of a STUN request has to be unpredictable, and the client takes it from the cryptographically secure random number generator.
Building and Running
The sample runs on the Native simulator - native_sim board without any network setup when it uses the sockets of the host:
west build -b native_sim samples/net/stun -- -DEXTRA_CONF_FILE=nsos.conf
west build -t run
For a board that is connected to a network:
west build -b <board to use> samples/net/stun
west flash
To ask another server, here one in the local network that is reached over IPv6:
west build -b <board to use> samples/net/stun -- -DCONFIG_NET_SAMPLE_STUN_SERVER=\"2001:db8::2\"
west flash
Sample Output
*** Booting Zephyr OS build v4.5.0 ***
[00:00:00.050,000] <inf> net_config: Initializing network
[00:00:02.050,000] <inf> net_config: Running dhcpv4 client...
[00:00:07.620,000] <inf> net_config: IPv4 address: 192.0.2.10
[00:00:07.620,000] <inf> net_stun_sample: Waiting for network...
[00:00:07.620,000] <inf> net_stun_sample: Network ready
[00:00:07.620,000] <inf> net_stun_sample: Asking stun.cloudflare.com port 3478
[00:00:07.680,000] <inf> net_stun_sample: Public address: 203.0.113.7
If no answer comes, the sample says so after the time
CONFIG_NET_SAMPLE_STUN_TIMEOUT_MS allows, 5 seconds by default. A firewall
that drops UDP is the usual reason.