The Linux host command returns:

hostA.domain.com has address xx.xxx.xxx.xx

How do I get just the IP address and put it in the $ipaddr variable?

open(FILE, "hostlist.txt") or die("Unable to open file");
@hostnames = <FILE>;
foreach $hostname (@hostnames)
    $lookup = qx(host $hostname);
    $ipaddr = grep ip_address $lookup;  <---- need help here
    print $ipaddr;

Since you posted this on the Unix & Linux site, instead of StackOverflow, I'm wondering if something like this isn't what you're looking for:

cat hostlist.txt | xargs resolveip -s

This will only return one IP address though.

Some hostnames will have multiple IP addresses associated with them:

$ host www.google.com
www.google.com is an alias for www.l.google.com.
www.l.google.com has address
www.l.google.com has address
www.l.google.com has address
www.l.google.com has address
www.l.google.com has address

To get just the list of IPs, one way to do it is:

host <hostname> | grep "has address" | awk '{print $4}'

If you want to stick with Perl, using resolveip:

$ipaddr = qx(resolveip -s $hostname);

Or to get all of the IPs, without executing any shell commands:

use Socket;
@ipaddrs = map { inet_ntoa($_) } (gethostbyname($hostname))[4,];
  • Note the , which makes it special to grab all the addresses :-) Example: @addresses = gethostbyname($name) or die "Can't resolve $name: $!\n"; @addresses = map { inet_ntoa($_) } @addresses[4 .. $#addresses]; # @addresses is a list of IP addresses ("", "") – Nikhil Mulley Jan 17 '12 at 12:29

Why not just use dig +short?


I'd use something like:


If you want something more exacting, then you'll probably have:


But even this is still somewhat loose. For example, it still allows '' to falsely match.

But both match the standard to


To add to @mkopala 's answer, if you have multiple hosts and you want to keep a track of them, build a hash, so that there is a easy reference of host to ip mapping.


use Socket;
@hostnames = ('www.google.com', 'www.yahoo.com', 'www.facebook.com');
%ipaddrs = ();
foreach $hostname (@hostnames) {
        map { $ipaddrs{$hostname} = inet_ntoa($_) } (gethostbyname($hostname))[4,];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.