Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting all IP addresses of a hostname

Tags:

perl

nslookup

I'm trying to get all the IP addresses for a host.

This is the nslookup output:

>>nslookup site.com

Server:         8.8.8.8
Address:        8.8.8.8#53

Non-authoritative answer:
Name:   site.com
Address: 1.1.1.1
Name:   site.com
Address: 2.2.2.2

I tried this code:

use Socket;
use Data::Dumper;
my $name = "site.com";
@addresses = gethostbyname($name)   or die "Can't resolve $name: $!\n";
@addresses = map { inet_ntoa($_) } @addresses[4 .. $#addresses];
print Dumper(\@addresses);

And this is the output:

['1.1.1.1'];

Anyway to get both 1.1.1.1 and 2.2.2.2?

like image 635
Navid Zarepak Avatar asked Sep 11 '18 13:09

Navid Zarepak


Video Answer


2 Answers

You can use Net::DNS::Resolver to get the IPv4 addresses (A records) for a hostname:

use warnings;
use strict;

use feature 'say';

use Net::DNS::Resolver;

my $res = Net::DNS::Resolver->new;

my $name = 'stackoverflow.com';
my $q = $res->query($name);

if ($q){
    print "$name has the following IPv4 addresses:\n";
    for ($q->answer){
        say $_->address if $_->type eq 'A';
    }
}

Output:

stackoverflow.com has the following IPv4 addresses:
151.101.65.69
151.101.193.69
151.101.1.69
151.101.129.69
like image 144
stevieb Avatar answered Oct 19 '22 03:10

stevieb


Simple pure perl to print the IP of the domain stackoverflow.com :

use Socket;
print join'.',unpack('C4',inet_aton('stackoverflow.com'));
print "\n";
like image 20
MUY Belgium Avatar answered Oct 19 '22 03:10

MUY Belgium