Easy way to get IP address from hostname using a Unix shell

hostnameipshellunix

What is the easiest way to get the IP address from a hostname?

I was thinking about trying a ping and parse it from the output. However, that doesn't seem very nice and will probably not work the same way on all systems.

I searched a bit around and found solutions with nslookup, but that doesn't work for hostnames in /etc/hosts.

Best Answer

You can do this with standard system calls. Here's an example in Perl:

use strict; use warnings;
use Socket;
use Data::Dumper;

my @addresses = gethostbyname('google.com');
my @ips = map { inet_ntoa($_) } @addresses[4 .. $#addresses];
print Dumper(\@ips);

produces the output:

$VAR1 = [
          '74.125.127.104',
          '74.125.127.103',
          '74.125.127.105',
          '74.125.127.106',
          '74.125.127.147',
          '74.125.127.99'
        ];

(On the command-line, the same script can be written as: perl -MSocket -MData::Dumper -wle'my @addresses = gethostbyname("google.com"); my @ips = map { inet_ntoa($_) } @addresses[4 .. $#addresses]; print Dumper(\@ips)')

You can do this similarly in other languages -- see the man page for the system calls at man -s3 gethostbyname etc.