开发者

Is it possible to resolve domain names to an IP address with PHP?

开发者 https://www.devze.com 2022-12-29 05:02 出处:网络
Well, very simple question. So that\'s good news for you, I guess. More thorough explanation: I have a PHP script allowing me to add urls to a database. I want the script to resolve the url to an IP

Well, very simple question. So that's good news for you, I guess.

More thorough explanation:

I have a PHP script allowing me to add urls to a database. I want the script to resolve the url to an IP address as well, to store that, too. However, some of the URLs are like this:

http://111.111.111.111/~example/index.php

So it also needs to work with that.

I'm not SURE that this is 开发者_开发知识库possible, but it only makes sense it would be.

So: Is it possible, and if so, how?


gethostbyname

echo gethostbyname('stackoverflow.com'); // 69.59.196.211

You can use parse_url to grab the host from the url:

$urlParts = parse_url('http://111.111.111.111/~example/index.php'); 

print_r($urlParts);

/*
Array
(
    [scheme] => http
    [host] => 111.111.111.111
    [path] => /~example/index.php
)
*/


gethostbyname()

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

It should be noted that if the website is on a shared hosting server, it is not guaranteed that your link will still be valid.


gethostbynamel() - Get a list of IPv4 addresses corresponding to a given Internet host name.


Usage:

$ips = gethostbynamel('stackoverflow.com');

/*
Array
(
    [0] => 69.59.196.211
)
*/
echo '<pre>';
print_r($ips);
echo '</pre>';

$ips = gethostbynamel('google.com');

/*
Array
(
    [0] => 74.125.39.105
    [1] => 74.125.39.106
    [2] => 74.125.39.147
    [3] => 74.125.39.99
    [4] => 74.125.39.103
    [5] => 74.125.39.104
)
*/
echo '<pre>';
print_r($ips);
echo '</pre>';

To get the host out of an URL you can use this one liner:

// 111.111.111.111
echo parse_url('http://111.111.111.111/~example/index.php', PHP_URL_HOST);


Yes, gethostbyname

http://us.php.net/manual/en/function.gethostbyname.php

0

精彩评论

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

关注公众号