get website ip using php

vkGunasekaran picture vkGunasekaran · Oct 15, 2011 · Viewed 11k times · Source

I need to fetch the given website ip address using php, that is ip address of server in which website is hosted.

For that i've used gethostbyname('**example.com*'). It works fine when the site is not redirected. for example if i used this function to get google.com, it gives "74.125.235.20".

When i tried it for "lappusa.com" it gives "lappusa.com". Then i tried this in browser it is redirecting to "http://lappusa.lappgroup.com/" . I checked the http status code it shows 200.

But i need to get ip address even if site was redirected, like if lappusa.com is redirected to lappusa.lappgroup.com then i need to get ip for redirected url.

How should i get this? any help greatly appreciated, Thanks!.

Answer

phihag picture phihag · Oct 15, 2011

The problem is not the HTTP redirect (which is above the level gethostbyname operates), but that lappusa.com does not resolve to any IP address and therefore can't be loaded in any browser. What your browser did was automatically try prepending www..

You can reproduce that behavior in your code. Also note that multiple IPs (version 4 and 6) can be associated with one domain:

<?php
function getAddresses($domain) {
  $records = dns_get_record($domain);
  $res = array();
  foreach ($records as $r) {
    if ($r['host'] != $domain) continue; // glue entry
    if (!isset($r['type'])) continue; // DNSSec

    if ($r['type'] == 'A') $res[] = $r['ip'];
    if ($r['type'] == 'AAAA') $res[] = $r['ipv6'];
  }
  return $res;
}

function getAddresses_www($domain) {
  $res = getAddresses($domain);
  if (count($res) == 0) {
    $res = getAddresses('www.' . $domain);
  }
  return $res;
}

print_r(getAddresses_www('lappusa.com'));
/* outputs Array (
  [0] => 66.11.155.215
) */
print_r(getAddresses_www('example.net'));
/* outputs Array (
  [0] => 192.0.43.10
  [1] => 2001:500:88:200::10
) */