Get a domain name's IP address with PHP

Posted in PHP -

It's easy to get the IP address for a domain name using PHP's gethostbyname() and gethostbynamel() functions. This post looks at some examples of using the gethostbyname() function in PHP to get a single IP address for a hostname.

Example domains used

The examples in this post use www.cnn.com and www.electrictoolbox.com. At the time of the writing of this post, www.cnn.com resolves to 4 possible IP addresses as follows:

$ nslookup www.cnn.com
Name:   www.cnn.com
Address: 157.166.226.26
Name:   www.cnn.com
Address: 157.166.255.18
Name:   www.cnn.com
Address: 157.166.224.26
Name:   www.cnn.com
Address: 157.166.226.25

and www.electrictoolbox.com resolves to a single IP address as follows:

$ nslookup www.electrictoolbox.com
www.electrictoolbox.com canonical name = electrictoolbox.com.
Name:   electrictoolbox.com
Address: 120.138.20.39

Using gethostbyname()

The PHP function gethostbyname() is very simple to use. Simply pass it the domain name you would like to look up and it will either return the IP address for that domain or the unmodified domain back again if it failed. If the domain has more than one IP address associated with it (as with www.cnn.com) then just a single IP address will be passed back.

Example 1

$x = gethostbyname('www.electrictoolbox.com');
var_dump($x);
// outputs string(13) "120.138.20.39"

Example 2

$x = gethostbyname('www.cnn.com');
var_dump($x);
// string(14) "157.166.255.19"
// OR string(14) "157.166.255.18"
// OR string(14) "157.166.224.26"
// OR string(14) "157.166.224.25"

Example 3

This example is for a non-existant domain and returns the domain itself instead of an IP address:

$x = gethostbyname('www.blah.foo');
var_dump($x);
// outputs string(12) "www.blah.foo"

If you needed to do something based on the IP address not being found, you could do something like this:

$domain = 'www.blah.foo';
$ip = gethostbyname($domain);
if($domain != $ip) {
    // do something
}

Note that not being able to find an IP address for the domain does not mean the domain does not exist, or even that a record does not exist for this (sub)domain. The DNS lookup may simply have failed.

Using gethostbynamel()

The PHP gethostbynamel() function returns a list of IP addresses for a domain and I will look at some examples of using this function on Monday.



Related posts:


Comments