目標: 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];
}