9

I am developing a PHP application that will be run only on the local network of a business. The application will be installed to the server using a custom installer like thing we made using 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.

The problem is I cannot get the LOCAL IP of the server.

I have tried

SERVER_NAME ( Displays just 127.0.0.1 )

REMOTE_ADDR ( Displays client external 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.

I just want to display the LOCAL IP of the server upon access directly from the server through http://localhost itself.

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. 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. Anyone can deploy it on their computer running Windows,Mac or 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. The application will be run only on the local network and not on the internet.

It should show the local IP just like the Android app called Air Droid does. Screenshot : https://lh3.ggpht.com/PmLopRm-Lj9WTnzm2MBI-bTbCLopAyqtd4C_4nvyDwLg8X0QwDbBbEREdWGHG5xku4s

0

8 Answers 8

12

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. Some/all/none of those may have the web service available on them. 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. 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. 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.
  • If you used a DNS name to access the page, gethostbyname($_SERVER['HTTP_HOST']); will turn that DNS name into an IP address.
  • $_SERVER['SERVER_NAME'] contains the name that has been configured in the web server configuration as it's server name. If you going to use this, you might as well just hard code it in PHP.
  • $_SERVER['SERVER_ADDR'] will contain the operating system of the server's primary IP address. 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. 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.

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.

2
  • Thank you for your advice. It really makes sense. If the server is connected to 2 networks (eg. a laptop connected to Ethernet and WiFi) I agree it will be highly unreliable to choose the correct network and IP. I didn't think of it that way. BTW making the user find his IP address on his own makes the application less n00b friendly though. :(
    – ajaybc
    Mar 28, 2012 at 10:58
  • 1
    @ajaybc That's what DNS is for... if it's all local, you can just use machine names to access the network, if it's over the internet, point a domain/subdomain's A record at your IP ;-)
    – DaveRandom
    Mar 28, 2012 at 11:05
3

Solutions:

  1. hardcode in php (upon installation one should edit this in your scripts)
  2. setup a variable in apache environment so that could be accessed through php (upon installation one should add this to apache's config)
  3. parse ifconfig -l or ipconfig -a output to determine IP addresses of the machine's network interfaces, exclude loopback interfaces. In the best case you'll receive one IP address - and that'll be the address you need, adding $_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']. Also you could put a /ping.php file with some kind of echo "my application"; to determine your IP address if the machine runs several HTTP servers on different IP addresses.
1
  • Well, I'd use the third part. But the PHP should be able to do exec() and use different parsing algorythms, depending on OS - ipconfig -a for windows, ifconfig -l for unix, etc. Mar 28, 2012 at 11:26
2

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. 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). The SERVER_ADDR variable shows the IP address that was used to call a PHP script; this information is passed from the web server, so it won't help for a PHP script that's running stand-alone (i.e. from a 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? 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. 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.

2
  • I am developing a cross platform PHP server application kind of thing. 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. Anyone can deploy it on their computer.
    – ajaybc
    Mar 28, 2012 at 11:05
  • Okay, well, if you don't even know what operating system people will be running your application on, or whether SAFE MODE is turned on, then a shell tool won't help with this. As I say, if you can describe the problem you're trying to solve rather than the solution you've come up with, we can help solve that problem rather than helping to implement your solution.
    – ghoti
    Mar 28, 2012 at 11:07
2

If you want to get Lan IP Adress Like 192.168.x.x You can use the following code:

I'm using this and fulfills my requirement perfectly. (only tested in windows machine)

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. =)

1
  • 3
    ipconfig is Windows only. Not very useful.
    – kodeart
    Apr 12, 2014 at 1:57
0

You can see all the available information with the command:

print_r($_SERVER, 1);
0

Try :

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

EDIT :

A bit hacky, but it seems to work :

<?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..

2
  • Sorry, this doesn't work. Because it shows 127.0.0.1. What I want is an IP like 192.168.1.6 which is the local IP of the server
    – ajaybc
    Mar 28, 2012 at 10:40
  • Tried your edit too. But it just gets the external ip of the server. What I need is the local ip of the server. Thanks
    – ajaybc
    Mar 28, 2012 at 10:54
0

Try using "ifconfig en1 inet" Command.

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

Output:- inet 192.168.. netmask 0xffffff00 broadcast 192.168.*.255

1
  • ifconfig is not for windows Oct 20, 2015 at 14:26
-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

$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"
1
  • Code only answers are discouraged
    – klutt
    Apr 26, 2022 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.