So far I have tried:
echo gethostbyname(gethostname());
But this give me the "local" IP (not sure if that's the right term) 127.0.0.1
, whereas I want the "public" IP address.
Eg, for the website stackoverflow.com I get 151.101.193.69
when using the website service https://ipinfo.info ... that is what I am looking for.
Use this code,
function getIPAddress() {
//whether ip is from the share internet
if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
//whether ip is from the proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
//whether ip is from the remote address
else{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
gethostbyname("example.com");
returns a IPv4 of specified server/domain
more on that: https://www.w3schools.com/php/func_network_gethostbyname.asp
So to get the external IP of your server you have to specify the domain name, because gethostname()
will return local IP address
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.