Need to find the IP address of a network interface on Ubuntu using PHP

I need help finding my computer's IP address when it is online. I am creating a system such as a kiosk that will be placed in different locations, and I need to be able to use a web browser to find the IP address of this computer on the local network.

If I use $_SERVER['SERVER_ADDR'] , I get the IP address through which I connect through the local browser (127.0.0.1) on this computer.

I cannot call and receive a public IP address because the blocks may be behind the router, and I do not want the public IP address of the router.

I need to find the IP address of this window on the server (ex: 192.168.0.xxx)

I know that when I do "ip addr show" from the terminal, I get

 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: em1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000 link/ether 61:a6:4d:63:a2:80 brd ff:ff:ff:ff:ff:ff inet 192.168.0.211/24 brd 192.168.0.255 scope global em1 inet6 fe80::62a4:4cff:fe64:a399/64 scope link valid_lft forever preferred_lft forever 

When I try:

 $command="ip addr show"; $localIP = exec ($command); 

$localIP exits with "valid_lft forever preferred_lft forever", but no other information. If I can get all this in $localIP , then I can filter the inet IP, but it won’t give me everything.

Is there an easier way to do this or something that I am missing when trying to execute the ip addr show command? In addition, I run apache as a user and cannot run it as root for this application.

+2
source share
11 answers

As described in exec() , only the LAST output string from the exec'd command is returned from the function. To capture all the output, you must use the optional second argument to the function:

 $last_line = exec('ip addr show', $full_output); ^^^^^^^^^^^^ 

$full_output will be an array of output lines from exec.d.

+4
source

The server (should) know how to resolve the hostname to the correct IP address, even if it is not connected to the Internet.

So, all you have to do is get the host name and then resolve the host name to an IP address. Something like this should work fine for you:

 $ip = gethostbyname(gethostname()); 

Regardless of whether the hostname is registered in DNS, the file / etc / hosts or even ActiveDirectory, as long as it is resolvable in some way, this will provide you with a resolved IP address.

You may also have to plan other options. Therefore, check what worked above, if it is not, then you need to return to other parameters:

  • $_SERVER['HTTP_HOST'] contains the address that was entered in the address bar of the browser to access the page. If you 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 the DNS name to access the page, gethostbyname($_SERVER['HTTP_HOST']) ; will turn this DNS name into an IP address.
  • $_SERVER['SERVER_NAME'] contains the name configured in the web server configuration as the server name. If you are going to use this, you could just simply copy it into PHP.
  • $_SERVER['SERVER_ADDR'] will contain the operating system the primary IP address of the server. This may or may not be the IP address that was used to access the page, and it may or may not be the IP address of the web server attached to it. This is highly dependent on the OS and server configuration. if the server has one IP address, this is probably a safe bet, although there are situations where it may contain 127.0.0.1 .

You can try something like:

 <?php $ip = gethostbyname(gethostname()); // if we didn't get an IP address if ($ip === gethostname()){ // lets see if we can get it from the // configured web server name $ip = gethostbyname($_SERVER['SERVER_NAME']); // if we still don't have an IP address if ($ip === $_SERVER['SERVER_NAME']){ // Then we default to whatever the OS // is telling us is it primary IP address $ip = $_SERVER['SERVER_ADDR']; } } 

If you want to use the command line (a dangerous, potential attack vector) on linux, you can do something like:

 //then all non 127.0.0.1 ips should be in the $IPS variable echo exec('/sbin/ifconfig | grep "inet addr:" | grep -v "127.0.0.1" | cut -d: -f2 | awk \'{ print $1}\'', $IPS); $ip = ''; $foundIps = count($IPS); switch($foundIps){ case 0: print "Crud, we don't have any IP addresses here!\n"; $ip = '127.0.0.1'; break; case 1: print "Perfect, we found a single usable IP address, this must be what we want!\n"; $ip = $IPS[0]; break; default: print "Oh snap, this machine has multiple IP addresses assigned, what you wanna do about that?\n" // I'm crazy, I'll just take the second one! $ip = $IPS[1]; } 
+4
source

This is a simple function that, using the /etc/network/interfaces will return you the public and private IPv4 address settings for eth0 and eth1

 function getIps() { $ifs_raw=file('/etc/network/interfaces'); $tocheck=array('eth0','eth1'); foreach($tocheck as $if) { foreach($ifs_raw as $idx=>$line) { if(strpos($line,"iface {$if} inet static")!==false) { $address=$ifs_raw[$idx+1]; $address=trim($address);$address=ltrim($address,"\t");$address=rtrim($address,"\t"); list($address_text,$addrip)=explode(" ",$address); if($address_text=='address') { if(filter_var($addrip, FILTER_VALIDATE_IP) !== false) { //Valid IP if(false===filter_var($addrip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) { $ips['private']=$addrip; } else { $ips['public']=$addrip; } } } } } } return $ips; } 
+1
source

SIMPLE TEAM FIND AN UNIX IP ADDRESS

 ip route | grep src | awk -F 'src' '{print $NF; exit}' | awk '{print $1}' 

Tested on RHEL / CentOS / OEL / Ubuntu / Fedora

+1
source

$_SERVER['REMOTE_ADDR']; gotta do the trick.

And if that doesn't work, you can always mess with shell_exec($command); . But keep in mind that you need to set permissions on the php file to execute.

0
source

The web interface configuration in debian / ubuntu is in the / etc / network / interfaces file. You can read if the php cgi process is not chrooted and see this file, you can parse it and get the ip address. Its easy to read. Something like this should work ...

 $myFile = "/etc/network/interfaces"; $fh = fopen($myFile, 'r'); $theData = ""; $resoult = ""; while(! feof($file)){ $theData = fgets($fh); if($theData == "iface em1 inet static"){ while(! feof($file)){ $theData = fgets($fh); if(split(" ",$theData)[0] == "address"){ $resoult = split(" ",$theData)[1]; brake; } } brake; } } fclose($fh); echo $resoult; 
0
source

Ok, I found a solution ....

Bubba → You decided to return the address 127.0.0.1. The box domain is demo01.com and it looks like it is pulling out the local address of 127. I tried to call the php file using a web browser on this computer along with the browser from another computer using the actual address 192.168.x and it gave me the address 127.0 .0.1 both times.

Paulina -> The IP address is dynamically set by the host router. Since this happens in several places, I cannot encode the IP address into boxes. I don’t know whether hardcoding in it will have anything to do with it or not, but I got the contents of the file, but they don’t have an IP address: # This file describes the network interfaces available on your system # and how to activate them. For more information, see Interfaces (5).

 # The loopback network interface auto lo iface lo inet loopback # The primary network interface #auto em1 #iface em1 inet dhcp 

Marc B → Your solution, which worked for me. I did not know that I needed to add this second variable to the call in order to display it. I can parse the IP address from there. Since this is only for display to the person who sets up the kiosk, if for some reason there are several addresses, I can pull out each of them and display a list, and then they can play a hit and skip, it will be only 2 IP they probably must worry anyway (lan and wan)

I don’t have enough juice to raise your answer to the answer if I could. But I am grateful and thank you!

Joren -> This will not work for my needs, remote_address returns the address of the computer calling the script. If I call it from a remote computer, I’m going to get the IP address of this computer, if I call it from a browser, I either need to know the address of this field in order to put it in the address bar (which I don’t know, t, and therefore I need script) or call it from 127.0.0.1 or localhost in which I get 127.0.0.1 as an answer anyway.

0
source

If you just want to use a specific interface, you can use this

 $ip = `ifconfig en1 inet | grep inet | awk '{print $2}'` 

output is just the ip of this interface

0
source

You can use this library that I wrote. he can read / write / etc / network / interfaces

https://github.com/carp3/networkinterfaces

 <?php //include composer autoloader include 'vendor/autoload.php'; // 'import' NetworkInterfaces class use NetworkInterfaces\Adaptor; use NetworkInterfaces\NetworkInterfaces; // create new handle from /etc/networking/interfaces $handle = new NetworkInterfaces('/etc/networking/interfaces'); // parse file $handle->parse(); // change eth0 ip address $handle->Adaptors['eth0']->address = '192.168.0.30'; // Write changes to /etc/networking/interfaces $handle->write(); 
0
source

edit / etc / sudoers to allow www-data to execute any command

ini php code:

  $output = shell_exec("sudo ifconfig"); echo "<pre>$output</pre>"; 
0
source

If there are several network adapters, data transfer is carried out in matrix order.

See the code below for Raspberry Pi or Ubuntu Linux.

 $ifs = exec("netstat -rne | grep -v ' Iface' | grep 'UG ' | awk '{print $5, $8}'"); $interfaces = explode(PHP_EOL, $ifs); $networks = array(); foreach($interfaces as $eth) { list($metric, $ethname) = explode(" ", $eth); $ipaddr = exec("ifconfig ${ethname} | grep 'inet ' | cut -d: -f2 | awk '{print $2}'"); $networks[$metric] = array($ethname=>$ipaddr); } ksort($networks); print_r($networks); 

 Array ( [30] => Array ( [eth0] => 192.168.0.31 ) ) 
0
source

Source: https://habr.com/ru/post/1261773/


All Articles