php獲取本機(jī)真實(shí)IP地址實(shí)例代碼

字號:


    本文實(shí)例為大家分享了php獲取本機(jī)真實(shí)IP地址實(shí)例代碼,供大家參考。
    主要是獲取操作系統(tǒng)為win2000/xp、win7的本機(jī)IP真實(shí)地址,和獲取操作系統(tǒng)為linux類型的本機(jī)IP真實(shí)地址,具體內(nèi)容如下:
    function getLocalIP() {
     $preg = "/\A((([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\.){3}(([0-9]?[0-9])|(1[0-9]{2})|(2[0-4][0-9])|(25[0-5]))\Z/";
    //獲取操作系統(tǒng)為win2000/xp、win7的本機(jī)IP真實(shí)地址
     exec("ipconfig", $out, $stats);
     if (!empty($out)) {
      foreach ($out AS $row) {
       if (strstr($row, "IP") && strstr($row, ":") && !strstr($row, "IPv6")) {
        $tmpIp = explode(":", $row);
        if (preg_match($preg, trim($tmpIp[1]))) {
         return trim($tmpIp[1]);
        }
       }
      }
     }
    //獲取操作系統(tǒng)為linux類型的本機(jī)IP真實(shí)地址
     exec("ifconfig", $out, $stats);
     if (!empty($out)) {
      if (isset($out[1]) && strstr($out[1], 'addr:')) {
       $tmpArray = explode(":", $out[1]);
       $tmpIp = explode(" ", $tmpArray[1]);
       if (preg_match($preg, trim($tmpIp[0]))) {
        return trim($tmpIp[0]);
       }
      }
     }
     return '127.0.0.1';
    }
    以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。