Good way to send/receive UDP packets?

wjoe invalid at example.com
Wed Jul 22 13:17:11 UTC 2020


On Tuesday, 21 July 2020 at 18:35:34 UTC, notna wrote:
> well, I guess all your remarks are true... and irrelevant at 
> the same time.
>
> please go back and read his first post.... starts with "I have 
> a project where I need to take and send UDP packets over the 
> Internet"...

... and continues with:

On Saturday, 18 July 2020 at 16:00:09 UTC, Dukc wrote:
> [...] And only communication with a single address, no need to 
> communicate with multiple clients concurrently.

Let me elaborate on why what I wrote is both, on topic and 
relevant at the same time:

It's a fundamental characteristic of UDP that you can't 
communicate with a single client only but you always are 
communicating with everyone who listens concurrently.

The combination of the Internet and theoretically only 65535 
available ports means that (mis)communication with other clients 
is likely to happen.
OP's client may receive datagrams that are broadcast on that port 
by other programs (port forwarding).
Likewise, other programs, which have a socket bound to the same 
port, may receive OP's data.

Examples:
- You behaving correctly yourself doesn't make others behave 
correctly now or retroactively.

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

- Checking a magic byte at offset 0 followed by the size isn't 
good enough.
Let's say I decide my magic is a word because I want to be able 
to determine byte order - I choose 0x015a.
When I broadcast a packet, e.g. [[0x015a], [0x0, 0x5a, 0xff]], 
but because I sent this from a little endian machine, the 
datagram will be delivered like so [0x5a, 0x01, 0x0, 0x5a, 0xff].
When OP's client receives this message it goes like so:
Read 2 bytes: [0x5a, 0x1]
  0x5a, oh that's me, 0x01 aha length of 1 byte - except it's not 
even a valid packet in the context of their program...

Using UDP in a good way is far more complicated than it first 
appears to be.



More information about the Digitalmars-d-learn mailing list