目标: openWRT Web 环境 php 脚本获取本机公网 IP, 以及本机IP、网关和DNS信息
获取本机公网 IP 地址函数
function getPublicIP() {
$init = curl_init('http://www.cip.cc');
curl_setopt($init, CURLOPT_RETURNTRANSFER, true);
$s_result = curl_exec($init);
//preg_match_all('/\b\d+\.\d+\.\d+\.\d+/',$a,$matches);
preg_match('/\b\d+\.\d+\.\d+\.\d+/',$s_result,$matches);
$s_ip = $matches[0];
return $s_ip;
}
获取本机本地IP、网关和DNS信息函数
function getMiddleString($input, $start, $end) {
$s_result = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));
return $s_result;
}
function getLocalNetInfo() {
$f_network = fopen("/etc/config/network", "r");
$s_network = fread($f_network,filesize("/etc/config/network"));
fclose($f_network);
$s_temp = getMiddleString($s_network,"'lan'","'wan'");
//echo $_temp . "\n";
$s_lan_ip = getMiddleString($s_temp,"ipaddr '","option gateway");
$s_lan_ip = substr($s_lan_ip,0,strpos($s_lan_ip, "'"));
//echo "lan ipaddr: " . $s_lan_ip;
//echo "\n";
$s_gateway = getMiddleString($s_temp,"gateway '","option dns");
$s_gateway = substr($s_gateway,0,strpos($s_gateway,"'"));
//echo "gateway: " . $s_gateway;
//echo "\n";
$s_dns = substr($s_temp,strpos($s_temp,"dns"));
$s_dns = substr($s_dns,strpos($s_dns,"'")+1);
$s_dns = substr($s_dns,0,strpos($s_dns,"'"));
//echo "dns: " . $s_dns;
$arr_result = array("ip"=>$s_lan_ip,"gateway"=>$s_gateway,"dns"=>$s_dns);
return $arr_result;
}
获取本地 LAN 联结设备
function getLanAllDevicesInfo() {
clearstatcache();
$f_arp = fopen("/proc/net/arp", "r");
$s_arp = fread($f_arp,filesize("/proc/net/arp")); // 此处 filesize 读取文件的长度为0,错误待查
// $s_arp = fread($f_arp,1000);
fclose($f_arp);
preg_match_all('/\b\d+\.\d+\.\d+\.\d+/',$s_arp,$matches);
return $matches[0];
}