Good way to send/receive UDP packets?

wjoe invalid at
Wed Jul 22 16:14:24 UTC 2020

On Wednesday, 22 July 2020 at 15:26:23 UTC, Dukc wrote:
> On Wednesday, 22 July 2020 at 13:17:11 UTC, wjoe wrote:
>> - Choosing a port which isn't in use right now isn't good 
>> enough because a few minutes later there may be another 
>> program using it, too, and for the same reason.
> But doesn't the UDP header include the sender IP address? So 
> together with the magic number, shouldn't it be good enough? I 
> know it definitely is not going to hold against jamming or a 
> man in the middle, but it isn't supposed to, at this stage. 
> It's used only for simulations that have the criticality of a 
> casual Tetris server.
> I do acknowledge that the needs may rise later on. And if so, I 
> understand that I'm much better off switching the protocol than 
> trying to hardening the UDP.

No, the UDP header includes the source and destination ports only.
For transmission over the internet the Internet Protocol (IP) is 
used, which contains, among other things, the source and 
destination addresses.

The anatomy looks like this:

[ -------- IP - Datagram ------ ]
            [ - UDP - Datagram - ]

But keep in mind that the destination address can be a broadcast 
address, like e.g., which you would use to 
announce your server to every PC in the network.
If you send a UDP datagram to a single address, however, it will 
still be delivered to every program on that PC which receives UDP 
datagrams from that port.

Also if you send UDP datagrams to multiple specific addresses, 
you need to send the same packet multiple times losing the major 
benefit of UDP - broadcast.
And packets with a broadcast address sent over the internet are 
dropped, as that would affect every connected PC.

If you are behind a router and send over the internet, your 
router will modify the IP-header, namely the sender address and 
replace that with your public address.
When receiving packets, the IP header contains the destination 
address of your public IP (the router), which it will translate 
to the local address according to the port forwarding setup.
That process is called network address translation (NAT) and is 
not only relevant for UDP.

More information about the Digitalmars-d-learn mailing list