#----------------------------- |
use IO:: Socket ; |
$server = IO:: Socket ::INET->new ( LocalPort => $server_port , |
Proto => "udp" ) |
or die "Couldn't be a udp server on port $server_port : $@\n" ; |
#----------------------------- |
while ( $him = $server -> recv ( $datagram , $MAX_TO_READ , $flags ) ) |
{ |
# do something |
} |
#----------------------------- |
# download the following standalone program |
#!/usr/bin/perl -w |
# udpqotd - UDP message server |
use strict; |
use IO:: Socket ; |
my ( $sock , $oldmsg , $newmsg , $hisaddr , $hishost , $MAXLEN , $PORTNO ); |
$MAXLEN = 1024; |
$PORTNO = 5151; |
$sock = IO:: Socket ::INET->new ( LocalPort => $PORTNO , Proto => 'udp' ) |
or die "socket: $@" ; |
print "Awaiting UDP messages on port $PORTNO\n" ; |
$oldmsg = "This is the starting message." ; |
while ( $sock -> recv ( $newmsg , $MAXLEN ) ) |
{ |
my ( $port , $ipaddr ) = sockaddr_in ( $sock ->peername ); |
$hishost = gethostbyaddr ( $ipaddr , AF_INET ); |
print "Client $hishost said ``$newmsg''\n" ; |
$sock -> send ( $oldmsg ); |
$oldmsg = "[$hishost] $newmsg" ; |
} |
die "recv: $!" ; |
#----------------------------- |
# download the following standalone program |
#!/usr/bin/perl -w |
# udpmsg - send a message to the udpquotd server |
use IO:: Socket ; |
use strict; |
my ( $sock , $server_host , $msg , $port , $ipaddr , $hishost , |
$MAXLEN , $PORTNO , $TIMEOUT ); |
$MAXLEN = 1024; |
$PORTNO = 5151; |
$TIMEOUT = 5; |
$server_host = shift ; |
$msg = "@ARGV" ; |
$sock = IO:: Socket ::INET->new ( Proto => 'udp' , |
PeerPort => $PORTNO , |
PeerAddr => $server_host ) |
or die "Creating socket: $!\n" ; |
$sock -> send ( $msg ) or die "send: $!" ; |
eval |
{ |
local $SIG {ALRM} = sub { die "alarm time out" }; |
alarm $TIMEOUT ; |
$sock -> recv ( $msg , $MAXLEN ) or die "recv: $!" ; |
alarm 0; |
1; |
# return value from eval on normalcy |
} or die "recv from $server_host timed out after $TIMEOUT seconds.\n" ; |
( $port , $ipaddr ) = sockaddr_in ( $sock ->peername ); |
$hishost = gethostbyaddr ( $ipaddr , AF_INET ); |
print "Server $hishost responded ``$msg''\n" ; |
#----------------------------- |