http://qs321.pair.com?node_id=129553


in reply to Simple UDP example anyone?

The question you've asked is two-part -- you want to both send and recieve a UDP message. chromatic addressed the former already, so I'll supply the latter. Here's a short script, using IO::Socket, which sends a UDP packet to some server, and then listens and prints out one (and one only) UDP packet that it gets in response.

#!/usr/bin/perl -w $|++; use strict; use IO::Socket; my $response = IO::Socket::INET->new(Proto=>"udp",LocalPort=>2424) or die "Can't make UDP server: $@"; my $message = IO::Socket::INET->new(Proto=>"udp",PeerPort=>4242,PeerAd +dr=>"chmrr.mit.edu") or die "Can't make UDP socket: $@"; $message->send("Ping!"); my ($datagram,$flags); $response->recv($datagram,42,$flags); print "Got message from ", $response->peerhost,", flags ",$flags || "n +one",": $datagram\n";

One thing to note is that we make the server to catch the response before we send out our query -- that way, the response can't "fall between the cracks," so to speak; it can't come back before we have the server up and ready. Another thing to note is that the "42" in there is the maximum length of the packet that the server will read. So if you get more data than this, it'll get truncated. Thus, you might want to make this rather big if you don't know how much data you'll be getting.

Just for kicks, I'll leave the above-mentioned computer (chmrr.mit.edu) running a UDP server on port 4242 so y'all can send it messages ad nauseum. ;> Here are the basics of the "server" that I'm running -- except the return UDP packet that you'll actually get may be more interesting than just "PONG!" Tip: Run it more than once. ;>

Update: I took it down, so you'll have to send UDP messages to yourself if you want to test it.

#!/usr/bin/perl -w $|++; use strict; use IO::Socket; my $server = IO::Socket::INET->new(LocalPort=>4242,Proto=>"udp") or die "Can't create UDP server: $@"; my ($datagram,$flags); while ($server->recv($datagram,42,$flags)) { my $ipaddr = $server->peerhost; print "Oooh -- udp from $ipaddr, flags ",$flags || "none",": $datagr +am\n"; my $response = IO::Socket::INET->new(Proto=>"udp",PeerHost=>$ipaddr, +PeerPort=>2424); $response->send("PONG!"); }

perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^+*`^ ve^#$&V"+@( NO CARRIER'