LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl: Get ip address of NIC (eth0) (https://www.linuxquestions.org/questions/programming-9/perl-get-ip-address-of-nic-eth0-425005/)

kenneho 03-15-2006 05:24 AM

perl: Get ip address of NIC (eth0)
 
Hi.


Anyone knows how to retreive the IP address of a network interface using Perl? I need to retreive the IP address of eth0.

druuna 03-15-2006 09:56 AM

Hi,

This is one way of doing just that:

Code:

#!/usr/bin/perl

$IP_eth0 = `ifconfig eth0`;
$IP_eth0 =~ s/.*inet addr:(.*)  Bcast:/1/;
print "IP eth0 => " . $1 . "\n";

It could be that the output of your ifconfig differs from mine. The relevant line looks like this: inet addr:192.168.101.11 Bcast:192.168.101.255 Mask:255.255.255.0 for my version. If your output differs you need to change the regular expression accordingly. If you don't know how, post the output of ifconfig eth0 and I/We will help.

Hope this helps.

kenneho 03-15-2006 10:48 AM

Quote:

Originally Posted by druuna
Hi,

This is one way of doing just that:

Code:

#!/usr/bin/perl

$IP_eth0 = `ifconfig eth0`;
$IP_eth0 =~ s/.*inet addr:(.*)  Bcast:/1/;
print "IP eth0 => " . $1 . "\n";

It could be that the output of your ifconfig differs from mine. The relevant line looks like this: inet addr:192.168.101.11 Bcast:192.168.101.255 Mask:255.255.255.0 for my version. If your output differs you need to change the regular expression accordingly. If you don't know how, post the output of ifconfig eth0 and I/We will help.

Hope this helps.



Thanks! I'll try it out some time later, but I'm sure it'll work. I'm using IPv6, but modifying the regular expression _should_ be manageable. :)

kenneho 03-18-2006 05:13 AM

It worked!

Again, thanks! Don't quite understand exactly _how_ the script works, though. :)

druuna 03-18-2006 05:56 AM

Hi,

A little breakdown of the commands:

1) $IP_eth0 = `ifconfig eth0`;
2) $IP_eth0 =~ s/.*inet addr: (.*) Bcast:/1/;
3) print "IP eth0 => " . $1 . "\n";

The first line is probably clear: fill $IP_eth0 with the output of the ifconfig eth0 command (ifconfig eth0 is not a pearl command, but a unix command).

The second line uses one of perl's regular expression ( s/regex/replacement/modifiers ) to 'cut out' the part you want.
In this case all the output stored in $IP_eth0 is checked and if the following .*inet addr: (.*) Bcast: is found, the part between the ( and ) can be represented as $1, so ( and ) are not part of the regular expression, they are special and can be used in the replacement part of the regular expression.

Take a look here perlrequick and here perlretut for a more detailed explanation.

The third line prints $1, which is what is set after the substitute command, the part between the ( and ), in the previous line.

Hope this clears things up.


All times are GMT -5. The time now is 02:45 AM.