简体   繁体   English

如何使用PHP获取服务器的本地IP地址?

[英]How do I get the local IP address of the server using PHP?

I am developing a PHP application that will be run only on the local.network of a business.我正在开发一个 PHP 应用程序,它将仅在企业的 local.network 上运行。 The application will be installed to the server using a custom installer like thing we made using Stunnix Advanced Webserver.该应用程序将使用自定义安装程序安装到服务器,就像我们使用 Stunnix Advanced Webserver 制作的一样。

As part of making the application more user friendly I am planning to display the LOCAL IP of the server so that it is extremely easy for the other computers in the.network to access the application by just typing this IP in their address bar.作为使应用程序更加用户友好的一部分,我计划显示服务器的本地 IP ,以便网络中的其他计算机只需在其地址栏中键入此 IP 即可轻松访问该应用程序。

The problem is I cannot get the LOCAL IP of the server.问题是我无法获取服务器的本地 IP

I have tried我努力了

SERVER_NAME ( Displays just 127.0.0.1 ) SERVER_NAME (仅显示 127.0.0.1)

REMOTE_ADDR ( Displays client external IP ) REMOTE_ADDR (显示客户端外部 IP)

SERVER_ADDR displays the correct IP but it does so only if I access it from a client using the IP which totally defeats its purpose. SERVER_ADDR显示正确的 IP 但只有当我使用 IP 从客户端访问它时它才会这样做,这完全违背了它的目的。

I just want to display the LOCAL IP of the server upon access directly from the server through http://localhost itself.我只想在通过http://localhost本身直接从服务器访问时显示服务器的本地 IP

I am somewhat sure that this isn't possible.我有点确定这是不可能的。 But if it is, please help.但如果是,请帮助。

EDIT编辑

I am developing a cross platform PHP server application kind of thing.我正在开发跨平台 PHP 服务器应用程序之类的东西。 We bundle Apache,PHP installers and a SQlite database as a one click installer alongside our PHP application to make it as user friendly as possible.我们将 Apache,PHP 安装程序和 SQlite 数据库作为一键式安装程序与我们的 PHP 应用程序捆绑在一起,以使其尽可能对用户友好。 Anyone can deploy it on their computer running Windows,Mac or Linux .任何人都可以在运行Windows、Mac 或 Linux的计算机上部署它。 After installing when the user opens the application on the server he can see the ip address [local ip] and port which can be used to connect to this server.安装后,当用户在服务器上打开应用程序时,他可以看到ip 地址 [本地 ip]和可用于连接到此服务器的端口。 The application will be run only on the local.network and not on the inte.net.该应用程序将仅在 local.network 上运行,而不在 inte.net 上运行。

It should show the local IP just like the Android app called Air Droid does.它应该显示本地 IP,就像名为 Air Droid 的 Android 应用程序一样。 Screenshot: https://lh3.ggpht.com/PmLopRm-Lj9WTnzm2MBI-bTbCLopAyqtd4C_4nvyDwLg8X0QwDbBbEREdWGHG5xku4s截图: https://lh3.ggpht.com/PmLopRm-Lj9WTnzm2MBI-bTbCLopAyqtd4C_4nvyDwLg8X0QwDbBbEREdWGHG5xku4s

The problem that you have here is that this is not a static piece of information. 你在这里遇到的问题是,这不是一个静态的信息。 Any given computer can have multiple IP addresses associated with multiple network cards. 任何给定的计算机都可以有多个与多个网卡相关联的IP地址。 Some/all/none of those may have the web service available on them. 部分/全部/全部可能都有可用的Web服务。 There may not be a single answer to the question you are asking of the OS. 您询问操作系统的问题可能没有一个答案。

If your server has a simple, single IP address configuration then you would probably be best to hard-code this - it is by far and away the simplest option. 如果您的服务器具有简单的单IP地址配置,那么您可能最好对其进行硬编码 - 它是迄今为止最简单的选项。 If you want to determine it dynamically, here are a few bits of information which you will hopefully find useful: 如果你想动态地确定它,这里有一些你希望有用的信息:

  • $_SERVER['HTTP_HOST'] contains the address that was typed into the address bar of the browser in order to access the page. $_SERVER['HTTP_HOST']包含在浏览器地址栏中输入的地址,以便访问该页面。 If you access the page by typing (for example) http://192.168.0.1/index.php into the browser, $_SERVER['HTTP_HOST'] will be 192.168.0.1 . 如果通过在浏览器中键入(例如) http://192.168.0.1/index.php来访问该页面, $_SERVER['HTTP_HOST']将为192.168.0.1
  • If you used a DNS name to access the page, gethostbyname($_SERVER['HTTP_HOST']); 如果您使用DNS名称访问该页面,则gethostbyname($_SERVER['HTTP_HOST']); will turn that DNS name into an IP address. 将该DNS名称转换为IP地址。
  • $_SERVER['SERVER_NAME'] contains the name that has been configured in the web server configuration as it's server name. $_SERVER['SERVER_NAME']包含已在Web服务器配置中配置的名称,作为其服务器名称。 If you going to use this, you might as well just hard code it in PHP. 如果您打算使用它,您也可以在PHP中对其进行硬编码。
  • $_SERVER['SERVER_ADDR'] will contain the operating system of the server's primary IP address. $_SERVER['SERVER_ADDR']将包含服务器主IP地址的操作系统。 This may or may not be the IP address that was used to access the page, and it may or may not be an IP address with the web server bound to it. 这可能是也可能不是用于访问页面的IP地址,它可能是也可能不是绑定了Web服务器的IP地址。 It depends heavily on OS and server configuration. 它在很大程度上取决于操作系统和服 if the server has a single IP address, this is probably a safe bet, although there are situations where this may contain 127.0.0.1 . 如果服务器有一个IP地址,这可能是一个安全的赌注,尽管有些情况下这可能包含127.0.0.1

The long of the short of it is that there is no 100% reliable way to determine a guaranteed working IP address of the web server, without examining information that was send to the web server in order to generate the page you are creating, which as you say totally defeats its purpose . 缺点是,没有100%可靠的方法来确定Web服务器的保证工作IP地址,而不检查发送到Web服务器的信息,以便生成您正在创建的页面,如你说totally defeats its purpose

Solutions: 解决方案:

  1. hardcode in php (upon installation one should edit this in your scripts) php中的硬编码(安装时应该在脚本中编辑)
  2. setup a variable in apache environment so that could be accessed through php (upon installation one should add this to apache's config) 在apache环境中设置一个变量,以便可以通过php访问(安装时应该将其添加到apache的配置中)
  3. parse ifconfig -l or ipconfig -a output to determine IP addresses of the machine's network interfaces, exclude loopback interfaces. 解析ifconfig -lipconfig -a输出以确定机器网络接口的IP地址,排除环回接口。 In the best case you'll receive one IP address - and that'll be the address you need, adding $_SERVER['SERVER_PORT'] . 在最好的情况下,您将收到一个IP地址 - 这将是您需要的地址,添加$_SERVER['SERVER_PORT'] If you'll get several IP addresses - you can try to query them all to check if they answer a HTTP requests on the $_SERVER['SERVER_PORT'] . 如果您将获得多个IP地址 - 您可以尝试查询它们以检查它们是否在$_SERVER['SERVER_PORT']上应答HTTP请求。 Also you could put a /ping.php file with some kind of echo "my application"; 你也可以在/ping.php文件中加入某种echo "my application"; to determine your IP address if the machine runs several HTTP servers on different IP addresses. 如果计算机在不同的IP地址上运行多个HTTP服务器,则确定您的IP地址。

If you want to get Lan IP Adress Like 192.168.xx You can use the following code: 如果您想获得Lan IP Adress Like 192.168.xx您可以使用以下代码:

I'm using this and fulfills my requirement perfectly. 我正在使用它并完美地满足我的要求。 (only tested in windows machine) (仅在Windows机器上测试)

function getLocalIP(){
    exec("ipconfig /all", $output);
        foreach($output as $line){
            if (preg_match("/(.*)IPv4 Address(.*)/", $line)){
                $ip = $line;
                $ip = str_replace("IPv4 Address. . . . . . . . . . . :","",$ip);
                $ip = str_replace("(Preferred)","",$ip);
            }
        }
    return $ip;
}

echo $ip = getLocalIP(); //This will return: 192.168.x.x (Your Local IP)

Hope this helps. 希望这可以帮助。 =) =)

I am also pretty sure this isn't possible. 我也很确定这是不可能的。 Or if it is possible, the results won't be reliable. 或者如果可能,结果将不可靠。

A server may have multiple IP addresses. 服务器可能有多个IP地址。 Also, the IP address used for HTTP on the server may not be the one used to reach the server from elsewhere (if there's a reverse proxy or NAT involved). 此外,服务器上用于HTTP的IP地址可能不是用于从其他地方到达服务器的IP地址(如果涉及反向代理或NAT)。 The SERVER_ADDR variable shows the IP address that was used to call a PHP script; SERVER_ADDR变量显示用于调用PHP脚本的IP地址; this information is passed from the web server, so it won't help for a PHP script that's running stand-alone (ie from a shell). 此信息是从Web服务器传递的,因此对于独立运行的PHP脚本(即从shell运行)无济于事。

Let's look at this another way. 让我们看看另一种方式。 What problem are you trying to solve? 你想解决什么问题? That is, why do you need the local IP of the server? 也就是说,为什么需要服务器的本地IP? Rather than getting help implementing a solution that won't work, let's look at the original issue and see if there's another solution that IS possible. 我们不是寻求实施无法解决的解决方案的帮助,而是看看原始问题,看看是否有另一种可能的解决方案。

I should point out that depending on your operating system, there may be ways to get a list of IPs assigned to various interfaces by parsing the output of a shell command like ifconfig -a or ip addr . 我应该指出,根据您的操作系统,可能有办法通过解析shell命令的输出来获取分配给各种接口的IP列表,如ifconfig -aip addr But I don't know your OS, so I can't suggest how that would work for you. 但是我不知道你的操作系统,所以我不能建议这对你有用。

$h = popen("ip addr | awk '/inet/{print$2}'");
$ip_list = array();
while ($ip_list[] = fread($h, 15)) { }
pclose($h);

You could put more logic into the PHP to avoid using awk in a pipe, but you get the idea. 您可以在PHP中添加更多逻辑以避免在管道中使用awk ,但是您可以理解。

Try using "ifconfig en1 inet" Command. 尝试使用“ifconfig en1 inet”命令。

print_r(exec("ifconfig en1 inet"));

Output:- inet 192.168. 输出: - inet 192.168。 . netmask 0xffffff00 broadcast 192.168.*.255 网络掩码0xffffff00广播192.168。*。255

Try : 试试:

<?php gethostbyname($_SERVER['SERVER_NAME']);

EDIT : 编辑:

A bit hacky, but it seems to work : 有点hacky,但似乎工作:

<?php
$str = file_get_contents("http://ip6.me/");
$pattern = "#\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b#";
preg_match($pattern, $str, $matches);
print_r($matches[0]);

But this rely on a third website.. 但这依赖于第三个网站..

您可以使用以下命令查看所有可用信息:

print_r($_SERVER, 1);

funciona bien en windows 10, sin embargo en windows 11 es diferente debi usar un metodo for para mejorar el codigo y hacerlo mas sencillo de echo le hare algunos ajustes funciona bien en windows 10, sin embargo en windows 11 es diferente debi usar un metodo for para mejorar el codigo y hacerlo mas sencillo de echo le hare algunos ajustes

$saldo_de_linea = '<br>';
$ipconfig =  ( shell_exec ("ipconfig/all"));
echo $saldo_de_linea;
$d = explode('Physical Address. . . . . . . . .',shell_exec ("ipconfig/all"));
$d1 = explode(':',$d[1]);
echo 'SEGMENTO_A 10: ' . $d1[10];
echo $saldo_de_linea;
echo 'your localhost ip use for xampp is ';
echo $saldo_de_linea;
echo $d1[10];
$mystring = $d1[10];
$findme   = '(';
$pos = strpos($mystring, $findme);
if ($pos === false) {
    echo "La cadena '$findme' no fue encontrada en la cadena '$mystring'";
} else {
    echo "La cadena '$findme' fue encontrada en la cadena '$mystring'";
    echo " y existe en la posición $pos";
}
echo $saldo_de_linea;
$ip_localhost_use_for_xampp = substr($mystring, 0, $pos);
echo $ip_localhost_use_for_xampp; // imprime "nas"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何获取局域网中使用php从本地服务器访问网页的系统的IP地址 - How can i get IP address of systems in a local network which accessing the webpage from local server using php 如何使用 PHP 获取服务器的外部 IP? - How do I get the external IP of my server using PHP? 我如何使用PHP获取本地系统IP地址 - how t0 i get the local system Ip Address using PHP 如何获取PHP中IP地址字符串的最后一部分 - How do I get the last part of an ip address string in PHP 如何在PHP中抓取IP地址并获取网站列表? - How do I crawl an IP address and get list of websites on it in PHP? 如何从CLI使用PHP获取服务器IP地址? - How can I get the server IP address using PHP from the CLI? 在 php 中使用 file_get_content() 时,如何设置 ip 地址? - How do i set ip address when using file_get_content() in php? 如何使用php获取发出请求的服务器地址的IP地址? - How to get the IP address of the server address on which the request came in using php? 我如何将我的 php 脚本放在我的 WAN IP 地址上,因为它目前在我的本地主机上? - How do I put my php script on my WAN IP address as it's currently on my local host? 如何使用本地IP地址而不是localhost访问数据库mysql服务器 - How can I access my database mysql server using my local ip address instead of using localhost
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM