Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get website ip using php

Tags:

php

hostname

ip

dns

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!.

like image 404
vkGunasekaran Avatar asked Oct 15 '11 09:10

vkGunasekaran


People also ask

How can I get IP address in PHP?

Using getenv() function: To get the IP Address,we use getenv(“REMOTE_ADDR”) command. The getenv() function in PHP is used for retrieval of values of an environment variable in PHP.

What is $_ server [' Remote_addr ']?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page. $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page.

How do I find the IP address of a user?

On the command prompt screen, type the words “ping host address,” where “host address” equals the address of the website you're looking to trace, and hit Enter. For example, if you want to find the IP address of Facebook, you would type the words “ping www.facebook.com” and then press enter.


1 Answers

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
) */
like image 68
phihag Avatar answered Oct 25 '22 02:10

phihag