php獲取使用者和伺服器ip及其地理位置詳解

2021-07-25 01:28:45 字數 1616 閱讀 2666

瀏覽器訪問獲取使用者ip:

/**

* php獲取使用者真實 ip

* 注意這種方式只適用於瀏覽器訪問時

注意:1、以上方式只適用於用瀏覽器訪問後台服務時可用 

2、以瀏覽器訪問和在後台直接執行php指令碼所生成的 $_server 變數是不同的

後台指令碼執行獲取伺服器ip:

<?php

/***方法一:使用 gethostbyname() 方法,此方法獲取的是內網ip

*/$realip = gethostbyname(gethostname());

print_r($realip);

echo "\n";

/***方法二:php執行linux系統命令 ifconfig

* 利用正規表示式獲取 ip

*/$output = shell_exec('ifconfig');

preg_match("/\d.\d.\d.\d/",$output,$realip );

print_r($realip [0]);

/***方法三:php執行linux系統命令 ifconfig ,此方法獲取外網ip

* 利用grep獲取 ip

*/$shell = "/sbin/ifconfig | grep -op '(?<=addr:).*(?=\s+b)' | sed '1d'";

$output = shell_exec($shell);

$shell = "/sbin/ifconfig | grep -op '(?<=addr:).*(?=\s+b)'";

$output = exec($shell);

return $output;

?>

注意:1、gethostname() 獲取的是 eth0 的ip,虛擬機器下linux沒有eth0項,所以當在虛擬機器下執行該方法時返回 127.0.0.1

其他方法解釋:

gethostbyname(string $hostname) : 獲取對應主機名的乙個ipv4位址

gethostbyaddr ( string $ip_address ) : 獲取指定的ip位址對應的主機名

gethostbynamel ( string $hostname ) : 獲取對應主機名的一系列所以ipv4位址

php獲取ip所屬城市:

/**

* php獲取 ip 地理位置

* **ip介面

* @return: array

*/function getcity($ip = '')

else

$data = (array)$ip->data;

}return $data['city'];

}

php獲取使用者和伺服器ip及其地理位置詳解

瀏覽器訪問獲取使用者ip php獲取使用者真實 ip 注意這種方式只適用於瀏覽器訪問時 注意 1 以上方式只適用於用瀏覽器訪問後台服務時可用 2 以瀏覽器訪問和在後台直接執行php指令碼所生成的 server 變數是不同的 後台指令碼執行獲取伺服器ip 方法一 使用 gethostbyname 方法...

java獲取本地IP和伺服器IP

string address inetaddress.getlocalhost gethostaddress tostring 這種方法能不能在linux伺服器上直接獲取ip有待驗證 設定異常資訊 param t 異常資訊。注意 這裡使用的是throwable來接收引數,為什麼不是使用excepti...

獲取當前網路IP和伺服器IP位址

獲取當前網路ip 對於通過多個 的情況,第乙個ip為客戶端真實ip,多個ip按照 分割 if ipaddress null ipaddress.length 15 return ipaddress 獲取伺服器位址 return ip位址 public static string getserveri...