Home / Get a list of IP addresses for a domain with PHP

Get a list of IP addresses for a domain with PHP

On Thursday I looked at how to get a domain name’s IP address with PHP using the gethostbyname() function. However some domains resolve to multiple IP addresses so this followup post looks at how to get a list of IP addresses for a domain in PHP using the gethostbynamel() function.

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 gethostbynamel()

The PHP function gethostbynamel() works in a similar way to the gethostbyname() function taking in a domain name as its single parameter but returning an array of IP addresses instead of a single IP address.

If the domain has only one IP address (as does www.electrictoolbox.com) then there will be a single element in the array; if the domain has multiple IP addresses (as does www.cnn.com) then there will be more than one element in the array.

Example 1

$x = gethostbynamel("www.electrictoolbox.com");
var_dump($x);
/*
output
array(1) {
  [0]=>
  string(13) "120.138.20.39"
}
*/

Example 2

$x = gethostbynamel("www.cnn.com");
var_dump($x);
/*
output
array(4) {
  [0]=>
  string(14) "157.166.226.26"
  [1]=>
  string(14) "157.166.255.18"
  [2]=>
  string(14) "157.166.224.26"
  [3]=>
  string(14) "157.166.226.25"
}
*/

Example 3

gethostbyname() returns the unmodified domain name if the IP address lookup failed. The gethostbynamel() function works differently, returning boolean false instead as shown in the following example:

$x = gethostbynamel("www.blah.foo");
var_dump($x);
/*
outputs
bool(false)
*/

So ideally to deal with the results of calling this function you’d need to do something like this:

$x = gethostbynamel("some.domain.here");
var_dump($x);
if(is_array($x)) {
    // do something
}