php获取本地ip地址,局域网ip获取
<?php
header("Content-type: text/html; charset=gb2312");
function getLocalIP(){
exec("ipconfig /all", $output);
foreach($output as $line){
if (preg_match("/(.*)IPv4(.*)/", $line)){
$ip = $line;
$ip = str_replace("IPv4 地址 . . . . . . . . . . . . :","",$ip);
$ip = str_replace("(首选)","",$ip);
}
}
return $ip;
}
echo $ip = getLocalIP();
在程序使用时由于使用utf-8,而默认系统为gbk,则考虑使用正则匹配来判断:
if (preg_match("/(.*)IPv4(.*)/", $line)){
$ip = preg_replace('/.*:/', '', $line);
$ip = preg_replace('/[^\d^\.]/', '', $ip);
}