Getting IP address and aliases in Perl

From lxadm | Linux administration tips, tutorials, HOWTOs and articles
Jump to: navigation, search

This piece of Perl code should get you IP address for eth0 into $ip variable:

my $ip;
my $device = "eth0";
if ((`/sbin/ifconfig $device`) =~ /inet addr:(\d+\.\d+\.\d+\.\d+)/) {
    $ip = $1;

If you’d also like to get a list of all aliases the device has, you could use something like:

my $device = "eth0";
my @ipaddr_output = `ip addr show dev $device`;
my @ip_aliases;
foreach my $ip_alias (@ipaddr_output) {
    if ($ip_alias =~ m/inet (.+)\/32(.+)$device(.+)/) {
        push (@ip_aliases, $1);

Note that if your locale is different, you may need to look for a different match (or just set locale in your perl script), i.e. see how it looks like in German:

$ ifconfig
eth0 Link encap:Ethernet Hardware Adresse 00:23:8b:eb:f2:b4
inet Adresse: Bcast: Maske:
$ ifconfig
eth0 Link encap:Ethernet HWaddr 00:23:8b:eb:f2:b4
inet addr: Bcast: Mask: