开发者

PHP - Domain to IP

I current have a system which works like this:

Insert IP and it will post the IP to another .php page. However, when I try post http://google.com it does not turn the domain into a IP.

How would I do that? E.g. when a user inserts http://google.com or any domain it will auto resolve the IP.

I know the function gethostbyadd, I dont know 开发者_开发技巧how to structure it out e.g. Forms, table, post data.

Thanks if any can help.


What have you got together so far? How is it failing?

A wild guess is that you're typing in http://google.com/ and trying to get an IP from that, and that will fail, as the URL contains protocol information as well. You need to pass the domain name, and only the domain name to gethostbyname:

gethostbyname('www.google.com'); // Works
gethostbyname('http://www.google.com'); // Will not work

If you have the protocol part (http://) in the beginning, you can use parse_url:

gethostbyname(parse_url('http://www.google.com', PHP_URL_HOST));

If you're having some other, specific problem, let us know. If you don't know where to start, I suggest start by reading up on a programming manual ;)


I think you're looking for gethostbyname:

$ip = gethostbyname('www.google.com');

Note, make sure you strip the http:// and any white space/trailing characters as this will likely prevent accurate results.


the function you are looking for is $x = gethostbyname('stackoverflow.com');


You probably need to look into using http://www.php.net/manual/en/function.gethostbynamel.php


In some people the function gethostbyname is running slowly or running once in a while. Some say that the apache needs rebooting to get the function started. I can not confirm this, but I want to give an alternative method how to find IP by Domain using nslookup

function getAddrByHost($host, $timeout = 1) {
   $query = `nslookup -timeout=$timeout -retry=1 $host`;
   if(preg_match('/\nAddress: (.*)\n/', $query, $matches))
      return trim($matches[1]);
}

echo getAddrByHost('example.com');

speed test using XHProf:

attempt 1

gethostbyname 5,014,593 microsec

getAddrByHost 29,656 microsec

attempt 2

gethostbyname 5,016,678 microsec

getAddrByHost 13,887 microsec

attempt 3

gethostbyname 5,014,640 microsec

getAddrByHost 8,297 microsec

Conclusion: the function gethostbyname is performed for more than 5 seconds, which is very long. Therefore, I advise you to use a faster function getAddrByHost

note: php use this file /etc/resolv.conf to get DNS servers:

In my case I use BIND (named) which works on the host 127.0.0.1

# /etc/resolv.conf
nameserver 127.0.0.1
nameserver 8.8.8.8
nameserver 4.4.4.4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜