How to find IP addresses for each interface in Perl?

I am trying to find a list of IPs in a linux window. Currently, my installation is a CentOS machine with several additional interfaces for eth0 for each VLAN. I am writing a script to find out if each VLAN IP address has a connection to specific IP addresses (different IP addresses for each network).

For instance:

  • eth0 has an IP address of 10.0.0.2 netmask 255.255.255.128

  • eth0.2 has an IP address of 10.0.130 netmask 255.255.255.128

  • eth0.3 has an IP address of 10.0.1.2 netmask 255.255.255.128

Each interface is currently configured for a static IP address through configuration files. However, I want 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 to determine which IP addresses are available. All I need to collect is just the IP address, not the device name.

+3
source share
4 answers

If you want a clean Perl solution, you can try IO :: Interface . I have had some success in the past and the documentation is good.

+5
source

There is a Net :: Interface that 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: if you mentioned: check the documentation for methods other than addressto get different information for each interface.

+6
source

ifconfig?

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

I think the following method is the most reliable and environment independent. But only useful if you know the name of the interface.

#!/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/

+1
source

Source: https://habr.com/ru/post/1773131/


All Articles