内网ip只能用于内部通信,而不能与其它网络互连。在tcp/ip协议中,专门保留了三个网段作为私有网段地址。分别如下:
10.0.0.0/8: 10.0.0.0~10.255.255.255
172.16.0.0/12: 172.16.0.0~172.31.255.255
192.168.0.0/16: 192.168.0.0~192.168.255.255
可以通过ifconfig命令查看本机的内网的ip地址,如我自己的是:
[root@iz2ze9ryeo103b85y5iy2wz ~]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.17.65.195 netmask 255.255.240.0 broadcast 172.17.79.255
ether 00:16:3e:06:72:82 txqueuelen 1000 (Ethernet)
RX packets 3185083 bytes 592616315 (565.1 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 2012465 bytes 740978713 (706.6 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
loop txqueuelen 1000 (Local Loopback)
RX packets 12524 bytes 3744309 (3.5 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 12524 bytes 3744309 (3.5 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
上面的172.17.65.195显然在私有网段区间内,也就是我这台服务器的内网ip地址。那么如何通过php获取这个地址呢?可通过如下代码实现:
function getLocalIp()
{
exec("ifconfig", $out, $stats);
if (!empty($out)) {
foreach ($out as $k => $row) {
if (isset($row) && (strstr($row, ' 10.') || strstr($row, ' 172.') || strstr($row, ':10.') || strstr($row, ':172.'))) {
$temp = ltrim($row);
break;
}
}
}
$data = explode(' ', $temp);
$pos = strpos($data[1], ':');
$ip = $pos ? substr($data[1], $pos+1) : $data[1];
return $ip;
}
显然在代码中实际上还是通过执行ifconfig命令获取到的。