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

Solution 1:

host <hostname>

Ex:

serv ~ $ host stackoverflow.com
stackoverflow.com has address 69.59.196.211

Edit

On Linux, (and some OS X variants, at least), you might be able to use resolveip, which is part of the MySQL server package:

/etc/hosts:
 ...
 127.0.0.1     localhost localhost.localdomain foo
 ...

serv ~ $ resolveip foo
IP address of foo is 127.0.0.1

Solution 2:

This ancient post seem to have many creative solutions.

If I need to make sure also /etc/hosts gets accessed, I tend to use

getent hosts somehost.com

This works, at least if `/etc/nsswitch.conf' has been configured to use files (as it usually is).


Solution 3:

For IPv4 there is a standard program which works out of the box using the resolver including /etc/hosts:

host="localhost"
ip="`gethostip -d "$host"`"

It is part of Debian, install it with:

apt-get install syslinux

For other protocols than IPv4 (like IPv6) I currently don't know a similar tool. Update: Because of this I just wrote a small tool which is capable to resolve IPv6, too:

https://github.com/hilbix/misc/blob/master/src/ipof.c

It is thought for a quick and dirty shell use like gethostip but allows IPv6, too:

ip="`ipof -6 -- heise.de`"

It also can be used interactively, for example:

ipof -a -d -x -v -h -

HTH


Solution 4:

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.


Solution 5:

Why not dig +short hostname ?

(query DNS)