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. |
Hi,
This is one way of doing just that: Code:
#!/usr/bin/perl Hope this helps. |
Quote:
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. :) |
It worked!
Again, thanks! Don't quite understand exactly _how_ the script works, though. :) |
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. |