I wish to detect if an address IP is local or external. In a web application, my customer wish to access files directly through samba on local network, and by a download link if you are not in the network.
I may just check if my IP is 172.30.*.*
, but it won't work anymore if my customer switch to a 10.*.*.*
or IPV6.
I may use a config var, so the customer may change it at will. I would like it to be automatic, with no config var.
How would you proceed ?
The external IP address or Public IP address is the IP address of the router interface that is connected to the Internet. Here is a diagram to illustrate the IP address allocation on a typical home or small business network. A router will typically have two network interfaces.
A public (or external) IP address is the one that your ISP (Internet Service Provider) provides to identify your home network to the outside world. It is an IP address that is unique throughout the entire Internet.
Update the list of IP ranges as you please. I haven't updated this list in awhile, but it should have most. Sorry, I never added IPv6 support to it.
function reserved_ip($ip)
{
$reserved_ips = array( // not an exhaustive list
'167772160' => 184549375, /* 10.0.0.0 - 10.255.255.255 */
'3232235520' => 3232301055, /* 192.168.0.0 - 192.168.255.255 */
'2130706432' => 2147483647, /* 127.0.0.0 - 127.255.255.255 */
'2851995648' => 2852061183, /* 169.254.0.0 - 169.254.255.255 */
'2886729728' => 2887778303, /* 172.16.0.0 - 172.31.255.255 */
'3758096384' => 4026531839, /* 224.0.0.0 - 239.255.255.255 */
);
$ip_long = sprintf('%u', ip2long($ip));
foreach ($reserved_ips as $ip_start => $ip_end)
{
if (($ip_long >= $ip_start) && ($ip_long <= $ip_end))
{
return TRUE;
}
}
return FALSE;
}
var_dump(reserved_ip('127.0.0.1')); // reserved (localhost)
var_dump(reserved_ip('74.125.140.101')); // not reserved (Google)
Unfortunately, there is no easy way to determine this with certainty. See my comment for an interesting example.
In IPv4 world, you can try doing this: determine your server's external IP address (using, for example http://ip-address.domaintools.com/myip.xml) and compare it with the client's socket remote address ($_SERVER['REMOTE_ADDR']
). If they are the same, then you are running on the same network, if they are different, then it's a different network.
In IPv6 world (properly deployed networks), there is no such thing as a private network and every device everywhere has its own public IP address. In this case, the only way to determine whether you're local or not is to maintain a full list of local devices.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With