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:
produces the output:
(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.