开发者

How can I find the IP addresses for each interface, in Perl?

开发者 https://www.devze.com 2023-01-23 08:14 出处:网络
I am trying to find a list of IP addresses on a linux box.Currently my setup is a CentOS machine with a few sub interfaces for eth0 for each VLAN.I am writing a script to see if each VLAN IP address h

I am trying to find a list of IP addresses on a linux box. Currently my setup is a CentOS machine with a few sub interfaces for eth0 for each VLAN. I am writing a script to see if each VLAN IP address has connectivity to certain IP addresses (different IP addresses for each network).

For example:

  • eth0 has an IP of 10.0.0.2 netmask 255.255.255.128

  • eth0.2 has an IP of 10.0.130 netmask 255.255.255.128

  • eth0.3 has an IP of 10.0.1.2 netmask 255.255.255.128

Each interface is currently set to static IP address via config files. However, I am wanting to change it from static to DHCP and get the same IP address. If I do this, it will break this part of the script:

@devarray 开发者_如何转开发= `cat /etc/sysconfig/network-scripts/ifcfg-eth0* | grep IPADDR=10 -B 10 | grep -v "#" | grep IPADDR`;

Is there a better way of determining what IP addresses are avaiable. All I need to gather is just the IP address and not the device name.


There is Net::Interface, which seems to give me good results on my system:

my %addresses = map { 
      ($_ => [
          map { Net::Interface::inet_ntoa($_) } # make addresses readable
              $_->address,                      # all addresses
      ]);
} Net::Interface->interfaces;                   # all interfaces

This will return something like

(
  eth0 => [],
  eth1 => [ '192.168.2.100' ],
  lo   => [ '127.0.0.1' ]
)

Update: Should've mentioned: Check the documentation for methods other than address to get at other information per interface.


If you want a pure Perl solution, you might try IO::Interface. I've had some success with it in the past, and the documentation is good.


How about using ifconfig?

my @ips = (`ifconfig -a` =~ /inet addr:(\S+)/g);


I think that the following method is the most reliable and environment-independent. But only useful if you known an interface name.

#!/usr/bin/perl
use strict;
use warnings;
use Socket;
require 'sys/ioctl.ph';

print get_interface_address('eth0');

sub get_interface_address
{
    my ($iface) = @_;
    my $socket;
    socket($socket, PF_INET, SOCK_STREAM, (getprotobyname('tcp'))[2]) || die "unable to create a socket: $!\n";
    my $buf = pack('a256', $iface);
    if (ioctl($socket, SIOCGIFADDR(), $buf) && (my @address = unpack('x20 C4', $buf)))
    {
        return join('.', @address);
    }
    return undef;
}

found here: http://snipplr.com/view/46170/the-most-reliable-and-correct-method-to-get-network-interface-address-in-linux-using-perl/

0

精彩评论

暂无评论...
验证码 换一张
取 消