Categories
Perl

Perl Convert List of Hostnames to IP4 Addresses

Instead of having to type nslookup over and over, let’s script a solution that queries a list. We can then redirect the output into a file and have a nice, CSV output – all automated.

Use this perl hostname to ip address converter like this:


perl converter.pl > output.csv

#!/usr/bin/perl
use warnings;
use strict;
use Socket;
# Finds ip of a list of hosts
# type:  perl ipfinder.pl > output.csv
# prints:
# 1.1.1.1,a.com
# 2.2.2.2,b.com
# 3.3.3.3,c.com
# some domains, like google.com for example, have multiple IP
# it will only report back the first ($addrs[0])
while (<DATA>) {
	my $uri = $_;
           # remove all spacing
	   $uri =~ s/\s+//g;
        # grab the data using gethostbyname()
	my ($name, $aliases, $addrtype, $length, @addrs) = gethostbyname $uri;
        # unpack $addrs[0], C4 says it's an unsigned int (octet)
	my ($a,$b,$c,$d) =  unpack('C4',$addrs[0]);
        # format the output and print it to stdout
	print "$a.$b.$c.$d,$uri\n";
}
__DATA__
a.com
b.com
c.com

2 replies on “Perl Convert List of Hostnames to IP4 Addresses”

Sometimes if I’m on a server that doesn’t have my scripts available, and I’m on Linux, I’ll just use the one-liner in bash below.
I’ll be giving a list of hostnames in hosts.txt and need the IP and/or FQDN. Of course it’s not CSV.
# for i in `cat hosts.txt`;do host $i | gawk {‘print $4,$1’} >> new_list.txt

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.