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.
使用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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.