PHP获取DHCP分配的本机IP

在搭建本地环境的时候,需要用到多个设备,有服务器、打印机连接接设备等。因为DHCP动态分配IP,所以每次重连都会发生IP地址的变更。

解决办法就是将每个设备的本机IP上传到统一的地方保存。因为使用REMOTE_ADDR和HTTP_X_FORWARDED_FOR等方法获取到的有可能是客户端使用的代理服务器的IP地址,并非真正的本机IP,解决办法就是针对mac下的查看IP地址命令:ifconfig 和 windows下的ipconfig,然后使用正则表达式从中获取到ip地址信息。

主要用到正则和exec方法。

<?php
$server = 'http://server.com/admin.php/xxx';
$agent = $_SERVER['HTTP_USER_AGENT'];
$os = '';
if (strpos($agent, 'Macintosh') !== false) {
        $os = 'mac'; 
}else{
        $os = 'win';
}
switch ($os) {
        case 'mac':
            uploadMacIP();
                break;
        case 'win':
                uploadWinIP();
        default:
                echo '未知操作系统类型';
                break;
}

function uploadMacIP()
{
        exec("whereis ifconfig",$out);
        $command = $out[0]." en0";
        exec($command, $output);
        $ip = '';
        foreach ($output as $k => $v) {
                if(preg_match("/inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/", $v, $matches)){
                        if($matches[0]){
                                $ip = str_replace("inet ", "", $matches[0]);
                        }
                }
        }
        if(!empty($ip)){
                uploadIP($ip,'mac');
        }
}
function uploadWinIP()
{
        $command = "ipconfig";
        exec($command, $output);
        $ip = '';
        foreach ($output as $k => $v) {
                if(preg_match("/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/", $v, $matches)){
                        if($matches[0]){
                                $ip = $matches[0];
                        }
                }
        }
        if(!empty($ip)){
                uploadIP($ip,'win');
        }
}
function uploadIP($ip,$os)
{
        $type = ['mac'=>1,'win'=>2];
        $data = [
                'ip' => $ip,
                'type' => $type[$os],
        ];
        $url = $server.'/add-ip';

        if(curl_post($url, $data)){
                echo '<h1>IP地址上传成功</h1>';
        }else{
                echo '<h1>IP地址上传失败</h1>';
        }
}
function curl_post($url,$data)
{
        $url .= "?data=".json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $server_output = curl_exec($ch);
        $info = curl_getinfo($ch);

        curl_close($ch);
        if($server_output == "OK"){
                return true;
        }else{ 
                return false;
        }
}
?>