in reply to Determining what NIC has an internet gateway

I use the following code/logic in Net::Pcap::FindDevice to find the interface with the default gateway:

# `netstat -rn` my $device_ip; my $re_if = $^O eq 'MSWin32' ? qr/^\s*(?:0.0.0.0)\s+(\S+)\s+(\S+)\s+/ : qr/^(?:0.0.0.0|default)\s+(\S+)\s+.*?(\S+)\s*$/; for (qx{netstat -rn}) { if ( /$re_if/ ) { $device_ip = $2; last; }; };

This gives me the IP address of the device. After that, it's just a matter of finding the corresponding Net::Pcap device, but that's of little oncernt to you :-)

Replies are listed 'Best First'.
Re^2: Determining what NIC has an internet gateway
by idsfa (Vicar) on Feb 18, 2006 at 22:54 UTC

    Unfortunately,

    1. There is no guarantee that the default interface actually connects to the internet (stupid, but not unknown)
    2. Some OSes can have multiple default routes

    A much easier method (and avoiding shelling out) is to create an IO::Socket::INET connection and then ask it which IP it binds to:

    use IO::Socket::INET; my $sock = IO::Socket::INET->new('www.google.com:80') or die "Can't bind : $@\n"; print 'IP Address with gateway to internet: ',$sock->sockhost(),"\n";

    Note that this does not identify which (physical or virtual) NIC has connectivity, but then, neither does the original code, so I am not sure that that was what was actually sought. IO::Interface offers functions to make that connection.


    The intelligent reader will judge for himself. Without examining the facts fully and fairly, there is no way of knowing whether vox populi is really vox dei, or merely vox asinorum. — Cyrus H. Gordon