您的位置:首页 > 编程语言 > PHP开发

php获取本机IP地址

2018-04-02 22:04 190 查看
<?php
function get_local_ip()
{
$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/";
//获取操作系统为win2000/xp、win7的本机IP真实地址
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]))) {
returntrim($tmpIp[1]);
}
}
}
}
//获取操作系统为linux类型的本机IP真实地址
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]))) {
returntrim($tmpIp[0]);
}
}
}
return '127.0.0.1';
}  
<?php
/**获取服务器ip地址
* @return array|false|string
*/
function get_server_ip()
{
$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/";
$os = Check_Domain_Helper::check_machine_os();
if ($os === 'Windows') {
//获取操作系统为win2000/xp、win7的本机IP真实地址
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]);
}
}
}
}
} else {
//获取操作系统为linux类型的本机IP真实地址
$result = shell_exec("/sbin/ifconfig");
if (preg_match_all("/inet (\d+\.\d+\.\d+\.\d+)/", $result, $match) !== 0)  // 这里根据你机器的具体情况, 可能要对“inet ”进行调整, 如“addr:”,看如下注释掉的if
// if (preg_match_all("/addr:(\d+\.\d+\.\d+\.\d+)/", $result, $match) !== 0)
{
foreach ($match [0] as $k => $v) {
if ($match [1] [$k] != "127.0.0.1") {
$the_local_ip = $match [1] [$k];
return $match [1] [$k];
}
}
}
}
return '127.0.0.1';
}
<?php
/**获取服务器ip地址
* @return array|false|string
*/
public
static function get_server_ip()
{
$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/";
$os = Check_Domain_Helper::check_machine_os();
if ($os === 'Windows') {
//获取操作系统为win2000/xp、win7的本机IP真实地址
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]);
}
}
}
}
} else {
//获取操作系统为linux类型的本机IP真实地址
$match = '';
exec("ifconfig", $result, $stats);
$result = implode("", $result);
$is_match = preg_match_all("/addr:(\d+\.\d+\.\d+\.\d+)/", $result, $match);

if ($is_match == 0) {
$is_match = preg_match_all("/inet (\d+\.\d+\.\d+\.\d+)/", $result, $match);
}
var_dump($match);

if ($is_match !== 0) {
foreach ($match [0] as $k => $v) {
if ($match [1] [$k] != "127.0.0.1") {
$the_local_ip = $match [1] [$k];
return $match [1] [$k];
}
}
}
}
return '127.0.0.1';
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PHP