I need to get local IP of computer like 192.*.... Is this possible with PHP?
I need IP address of system running the script, but I do not need the external IP, I need his local network card address.
$localIP = getHostByName(php_uname('n'));
$localIP = getHostByName(getHostName());
$_SERVER['SERVER_ADDR']
getHostName doesn't return the sites domain name.A reliable way to get the external IP address of the local machine would be to query the routing table, although we have no direct way to do it in PHP.
However we can get the system to do it for us by binding a UDP socket to a public address, and getting its address:
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock, "8.8.8.8", 53);
socket_getsockname($sock, $name); // $name passed by reference
// This is the local machine's external IP address
$localAddr = $name;
socket_connect will not cause any network traffic because it's an UDP socket.
$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_connect($sock, $this->getDockerMachineIp(), 53);sockets module should be installed and enabled on PHP.This is an old post, but get it with this:
function getLocalIp()
{ return gethostbyname(trim(`hostname`)); }
For example:
die( getLocalIp() );
Found it on another site, do not remove the trim command because otherwise you will get the computers name.
BACKTICKS (The special quotes): It works because PHP will attempt to run whatever it's between those "special quotes" (backticks) as a shell command and returns the resulting output.
gethostbyname(trim(`hostname`));
Is very similar (but much more efficient) than doing:
$exec = exec("hostname"); //the "hostname" is a valid command in both windows and linux
$hostname = trim($exec); //remove any spaces before and after
$ip = gethostbyname($hostname); //resolves the hostname using local hosts resolver or DNS
gethostbyname to return a loopback IP (e.g. 127.0.0.1) for the host machine.try this (if your server is Linux):
$command="/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'";
$localIP = exec ($command);
echo $localIP;
eth0 is the appropriate interface.wlan0 instead of eth0 and to replace 'inet addr:' with 'inet adr:', possibly due to the locale used on my system (fr_FR). Other than that, this answer was the solution I was looking for. Thanks!'inet adr:' worked in my terminal (french locale), but in the PHP script 'inet addr:' was the correct value (english locale, I guess).Depends what you mean by local:
If by local you mean the address of the server/system executing the PHP code, then there are still two avenues to discuss. If PHP is being run through a web server, then you can get the server address by reading $_SERVER['SERVER_ADDR']. If PHP is being run through a command line interface, then you would likely have to shell-execute ipconfig (Windows) / ifconfig (*nix) and grep out the address.
If by local you mean the remote address of the website visitor, but not their external IP address (since you specifically said 192.*), then you are out of luck. The whole point of NAT routing is to hide that address. You cannot identify the local addresses of individual computers behind an IP address, but there are some tricks (user agent, possibly mac address) that can help differentiate if there are multiple computers accessing from the same IP.
It is very simple and above answers are complicating things. Simply you can get both local and public ip addresses using this method.
<?php
$publicIP = file_get_contents("http://ipecho.net/plain");
echo $publicIP;
$localIp = gethostbyname(gethostname());
echo $localIp;
?>
You may try this as regular user in CLI on Linux host:
function get_local_ipv4() {
$out = split(PHP_EOL,shell_exec("/sbin/ifconfig"));
$local_addrs = array();
$ifname = 'unknown';
foreach($out as $str) {
$matches = array();
if(preg_match('/^([a-z0-9]+)(:\d{1,2})?(\s)+Link/',$str,$matches)) {
$ifname = $matches[1];
if(strlen($matches[2])>0) {
$ifname .= $matches[2];
}
} elseif(preg_match('/inet addr:((?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3})\s/',$str,$matches)) {
$local_addrs[$ifname] = $matches[1];
}
}
return $local_addrs;
}
$addrs = get_local_ipv4();
var_export($addrs);
Output:
array (
'eth0' => '192.168.1.1',
'eth0:0' => '192.168.2.1',
'lo' => '127.0.0.1',
'vboxnet0' => '192.168.56.1',
)
array('bond0'=>'10.66.42.83','bond1'=>'hosting Ip address','lo'=>'127.0.0.1', ) I got this. I added this code in php file,split() function has been DEPRECATED as of PHP 5.3.0. so suggest using explode() insteadI fiddled with this question for a server-side php (running from Linux terminal)
I exploded 'ifconfig' and trimmed it down to the IP address.
Here it is:
$interface_to_detect = 'wlan0';
echo explode(' ',explode(':',explode('inet addr',explode($interface_to_detect,trim(`ifconfig`))[1])[1])[1])[0];
And of course change 'wlan0' to your desired network device.
My output is:
192.168.1.5
To get the public IP of your server:
$publicIP = getHostByName($_SERVER['HTTP_HOST']);
echo $publicIP;
// or
$publicIP = getHostByName($_SERVER['SERVER_NAME']);
echo $publicIP;
If none of these global variables are available in your system or if you are in a LAN, you can query an external service to get your public IP:
$publicIP = file_get_contents('https://api.ipify.org/');
echo $publicIP;
// or
$publicIP = file_get_contents('http://checkip.amazonaws.com/');
echo $publicIP;
Get Local IPv4 Address, tested with RHEL:
function getLocalIPv4(){
return str_replace(array("\n", "\t", "\r"),'',shell_exec("nmcli | grep inet4 | awk '{print $2}' | cut -d/ -f1 2>&1"));
}
Even better, tested with RHEL:
function getLocalIPv4(){
return str_replace(array("\n", "\t", "\r", ' '),'',shell_exec('hostname -I 2>&1'));
}
Two things to note:
array("\n", "\t", "\r") you have to use quotes and not ticks, otherwise it won't remove the carriage return. Not sure why.... "\t" not needed really....if you have only one ip assigned to the server you can use the following code
$hostname = gethostname(); // Get the hostname of the current server
$host_ip = gethostbyname($hostname); // Get the primary IPv4 address associated with the hostname
or if there are multiple ips assigned to the server then you can use following
$host_ips = gethostbynamel(gethostname());
remember gethostbynamel returns an array of ips
I assume that you work on Windows. This code works fine, I'm using it in Laravel's serve command.
Hope it helps you!
$output = shell_exec('ipconfig');
if ($output === null) {
echo 'Unable to run "ipconfig" command' . PHP_EOL;
$output = shell_exec('ifconfig');
if ($output === null) {
echo 'Unable to run "ifconfig" command' . PHP_EOL;
return;
}
}
// Look for the section containing "Wi-Fi" or "Wireless LAN adapter Wi-Fi"
if (str_contains($output, 'Wireless LAN adapter Wi-Fi')) {
$sections = explode('Wireless LAN adapter Wi-Fi', $output);
// Check if we have the expected parts
if (isset($sections[1])) {
// Find the line with "IPv4 Address"
$lines = explode("\n", $sections[1]);
foreach ($lines as $line) {
if (str_contains($line, 'IPv4 Address')) {
// Extract the IP address
$parts = explode(':', $line);
if (isset($parts[1])) {
$ip = trim($parts[1]);
echo $ip . PHP_EOL;
}
}
}
}
}
$_SERVER['REMOTE_ADDR']
PHP_SELF Returns the filename of the current script with the path relative to the root
SERVER_PROTOCOL Returns the name and revision of the page-requested protocol
REQUEST_METHOD Returns the request method used to access the page
DOCUMENT_ROOT Returns the root directory under which the current script is executing