[英]Is public IP address?
I would like to know whether there is any easy method to check whether an IP address is publicly accessible or is private. 我想知道是否有任何简单的方法来检查IP地址是公开访问还是私有。
More specifically. 进一步来说。 I know for example, that 127.0.0.1 is a private IP address that point into the same machine, 255.255.255.255 if for broadcasting into the same network, 192.168.1.0 is for local network addresses and so on.
我知道例如,127.0.0.1是指向同一台机器的私有IP地址,如果用于广播到同一网络则为255.255.255.255,192.168.1.0用于本地网络地址,依此类推。 But how can I distinguish whether a given IP address is not one of the private IP and is publicly accessible?
但是,如何区分给定的IP地址是否属于私有IP并且是否可公开访问?
http://en.wikipedia.org/wiki/Private_network lists the various ranges. http://en.wikipedia.org/wiki/Private_network列出了各种范围。 Just construct an if statement.
只需构造一个if语句。
Pulic/private IPv4 addresses are defined in RFC 5735 . Pulic /私有IPv4地址在RFC 5735中定义。 In short:
简而言之:
For IPv6, refer to RFC 5165 . 对于IPv6,请参阅RFC 5165 。 In short:
简而言之:
Note that services on machines without a public IP may still be reachable from the internet with the help of port forwarding or other firewall rules. 请注意,在端口转发或其他防火墙规则的帮助下,仍可以从Internet访问没有公共IP的计算机上的服务。
function validateIpAddress($ip_addr)
{
$result = true;
if(preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/",$ip_addr))
{
$parts=explode(".",$ip_addr);
foreach($parts as $ip_parts)
{
if(intval($ip_parts)>255 || intval($ip_parts)<0)
$result=false;
}
if (intval($parts[0])==0 || intval($parts[0])==10 || intval($parts[0])==127 || (intval($parts[0])>223 && intval($parts[0])<240))
{
$result=false;
}
if ((intval($parts[0])==192 && intval($parts[1])==168) || (intval($parts[0])==169 && intval($parts[1])==254))
{
$result=false;
}
if (intval($parts[0])==172 && intval($parts[1])>15 && intval($parts[1])<32 )
{
$result=false;
}
}
else
{
$result = false; //if format of ip address doesn't matches
}
return $result;
}
One solution is mentioned by Ed Heal, but there is another one: Ed Heal提到了一个解决方案,但还有另一个解决方案:
Just connect to some external host and ask it for the IP it sees, like that (example for PHP): 只需连接到某个外部主机并询问它所看到的IP,就像那样(PHP的例子):
$my_public_ip = file_get_contents('http://ip.42.pl/raw');
This specific example I know will return single string containing only an IP address. 我知道的这个具体示例将返回仅包含IP地址的单个字符串。 I do not know other services offering this, although there are probably plenty of them.
我不知道提供这个的其他服务,虽然可能有很多。 The main page of the above script / service is: http://ip.42.pl/ .
上述脚本/服务的主页是: http : //ip.42.pl/ 。
If you know similar services, please post their URLs in the comments, so future readers have other options. 如果您了解类似的服务,请在评论中发布他们的网址,以便将来的读者有其他选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.