sub ListenOnUDP { my $end = time + $timeout; print "PortListen on $strFQDN ($address) at $strProtocol\/$intListenPort\n"; # Open a udp port my $hSocket = IO::Socket::INET->new(LocalPort=>$intListenPort, Proto=>$strProtocol, Timeout=>$timeout) or die "Can't create UDP socket: $@"; # Wait for a connection ($hSocket is undef until an accept call is made). my $rin = ''; vec($rin, fileno($hSocket), 1) = 1; while (1) { my $timeleft = $end - time; if ($timeleft <= 0) { print "No connection: Timed out after $timeout seconds.\n"; last; } my ($nfound, $t) = select(my $rout = $rin, undef, undef, $timeleft); if ($nfound == 0) { # either timeout or end of file print "No connection: Timed out after $timeout seconds.\n"; last; } # Connection exists; Receive data, open a response port, respond, then close both ports. my ($datagram,$flags); while ($hSocket->recv($datagram,42,$flags)) { my $ripaddr = $hSocket->peerhost; my $rport = $hSocket->peerport; print "RECIEVE_FROM-TO, $ripaddr, $strProtocol\/$rport, $address, $strProtocol\/$intListenPort, message=$datagram\n"; # UDP is connectionless, so try to open a connection going back the other way, then send a response. # NOTE: This requires a predefined 'remote' port. Pass via commandline; default is $intSendPort my $hResponseSocket = IO::Socket::INET->new(Proto=>$strProtocol,PeerHost=>$ripaddr,PeerPort=>$intSendPort); print "SEND_FROM-TO, $address, $strProtocol\/" . $hResponseSocket->sockport . ", $ripaddr, $strProtocol\/$intSendPort, message=PONG!\n"; $hResponseSocket->send("PONG!"); close($hResponseSocket); last; } last; } close($hSocket); }