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 > output.csv

use warnings;
use strict;
use Socket;
# Finds ip of a list of hosts
# type:  perl > output.csv
# prints:
# some domains, like 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";

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.