[perl]代码库
#-----------------------------
use Socket;
socket ( SOCKET, PF_INET, SOCK_DGRAM, getprotobyname ( "udp" ) )
or die "socket: $!";
#-----------------------------
use IO::Socket;
$handle = IO::Socket::INET->new ( Proto => 'udp' )
or die "socket: $@";
# yes, it uses $@ here
#-----------------------------
$ipaddr = inet_aton ( $HOSTNAME );
$portaddr = sockaddr_in ( $PORTNO, $ipaddr );
send ( SOCKET, $MSG, 0, $portaddr ) == length ( $MSG )
or die "cannot send to $HOSTNAME($PORTNO): $!";
#-----------------------------
$portaddr = recv ( SOCKET, $MSG, $MAXLEN, 0 ) or die "recv: $!";
( $portno, $ipaddr ) = sockaddr_in ( $portaddr );
$host = gethostbyaddr ( $ipaddr, AF_INET );
print "$host($portno) said $MSG\n";
#-----------------------------
send ( MYSOCKET, $msg_buffer, $flags, $remote_addr )
or die "Can't send: $!\n";
#-----------------------------
# download the following standalone program
#!/usr/bin/perl
# clockdrift - compare another system's clock with this one
use strict;
use Socket;
my ($host, $him, $src, $port, $ipaddr, $ptime, $delta);
my $SECS_of_70_YEARS = 2_208_988_800;
socket(MsgBox, PF_INET, SOCK_DGRAM, getprotobyname("udp"))
or die "socket: $!";
$him = sockaddr_in(scalar(getservbyname("time", "udp")),
inet_aton(shift || '127.1'));
defined(send(MsgBox, 0, 0, $him))
or die "send: $!";
defined($src = recv(MsgBox, $ptime, 4, 0))
or die "recv: $!";
($port, $ipaddr) = sockaddr_in($src);
$host = gethostbyaddr($ipaddr, AF_INET);
my $delta = (unpack("N", $ptime) - $SECS_of_70_YEARS) - time();
print "Clock on $host is $delta seconds ahead of this one.\n";
#-----------------------------