Message Passing
As we mentioned earlier, UDP communication involves much lower overhead but provides no reliability, since there are no promises that messages will arrive in a proper order—or even that they will arrive at all. UDP is often said to stand for Unreliable Datagram Protocol.
Still, UDP offers some advantages over TCP, including the ability to broadcast or multicast to a whole bunch of destination hosts at once (usually on your local subnet). If you find yourself getting overly concerned about reliability and starting to build checks into your message system, then you probably should just use TCP to start with. True, it costs more to set up and tear down a TCP connection, but if you can amortize that over many messages (or one long message), it doesn’t much matter.
Anyway, here’s an example of a UDP program. It contacts the UDP
time port of the machines given on the command line, or everybody it can
find using the universal broadcast address if no arguments were
supplied.[165] Not all machines have a time server enabled, especially
across firewall boundaries, but those that do will send you back a
4-byte integer packed in network byte order that represents what time
that machine thinks it is. The time returned, however, is in the number
of seconds since 1900. You have to subtract the number of seconds
between 1900 and 1970 to feed that time to the localtime or
gmtime conversion functions.
#!/usr/bin/perl # clockdrift – compare other systems' clocks with this one # without ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access