How can I capture incoming UDP traffic using IO::Socket in Perl?

97 views Asked by At

I am attempting to listen and continually grab incoming UDP traffic on port 162 as shown below, however, we never seem to enter the while loop.

The traffic is visible via tcpdump on port 162 and the Perl code below is running as root. The script seems to be waiting and listening but, never any output.

Surely missing a key bit. Any ideas?

use IO::Socket::INET;

# flush after every write
$| = 1;

my $received;
my ($peeraddress, $peerport);

my $socket = new IO::Socket::INET(
   LocalAddr => 'localhost',
   LocalPort => '162',
   Proto     => 'udp',
   Type      => SOCK_DGRAM,
) or die "ERROR in Socket Creation : $@\n";

while ( $socket->recv($received, 1024) ) {
   $peeraddress = $socket->peerhost();
   $peerport = $socket->peerport();
   print "\n($peeraddress , $peerport) said : $received";
}

$socket->close();

EDIT: the above code works when 'localhost' is replaced with '0.0.0.0', please see @ikegami 's answer. Also had the problem of traffic not reaching it because of the system firewall, as noted in comments.

1

There are 1 answers

1
ikegami On BEST ANSWER

You are listening to 127.0.0.1:162, but the traffic is going to another adapter.

Say you're behind a NAT router and your internet traffic goes to 192.168.1.2. You would need to listen to 192.168.1.2:162 instead of 127.0.0.1:162.

Alternatively, you can listen to 0.0.0.0:162. The special address 0.0.0.0 indicates you want to listen to all adapters, so both 127.0.0.1 and 192.168.1.2 in our example.