php get visitor's MAC address [duplicate] - php

I need to know the MAC and the IP address of the connect clients, how can I do this in PHP?

Server IP
You can get the server IP address from $_SERVER['SERVER_ADDR'].
Server MAC address
For the MAC address, you could parse the output of netstat -ie in Linux, or ipconfig /all in Windows.
Client IP address
You can get the client IP from $_SERVER['REMOTE_ADDR']
Client MAC address
The client MAC address will not be available to you except in one special circumstance: if the client is on the same ethernet segment as the server.
So, if you are building some kind of LAN based system and your clients are on the same ethernet segment, then you could get the MAC address by parsing the output of arp -n (linux) or arp -a (windows).
Edit: you ask in comments how to get the output of an external command - one way is to use backticks, e.g.
$ipAddress=$_SERVER['REMOTE_ADDR'];
$macAddr=false;
#run the external command, break output into lines
$arp=`arp -a $ipAddress`;
$lines=explode("\n", $arp);
#look for the output line describing our IP address
foreach($lines as $line)
{
$cols=preg_split('/\s+/', trim($line));
if ($cols[0]==$ipAddress)
{
$macAddr=$cols[1];
}
}
But what if the client isn't on a LAN?
Well, you're out of luck unless you can have the client volunteer that information and transmit via other means.

The MAC address of a client (in the sense of the computer that issued the HTTP request) is overwritten by every router between the client and the server.
Client IP is conveniently provided to the script in $_SERVER['REMOTE_ADDR']. In some scenarios, particularly if your web server is behind a proxy (i.e. a caching proxy) $_SERVER['REMOTE ADDR'] will return the IP of the proxy, and there will be an extra value, often $_SERVER['HTTP_X_FORWARDED_FOR'], that contains the IP of the original request client.
Sometimes, particularly when you're dealing with an anonymizing proxy that you don't control, the proxy won't return the real IP address, and all you can hope for is the IP address of the proxy.

I don't think you can get MAC address in PHP, but you can get IP from $_SERVER['REMOTE_ADDR'] variable.

For windows server I think u can use this:
<?php
echo exec('getmac');
?>

All you need to do is to put arp into diferrent group.
Default:
-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*
With command:
sudo chown root:www-data /usr/sbin/arp
you will get:
-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*
And because apache is a daemon running under the user www-data, it's now able to execute this command.
So if you now use a PHP script, e.g.:
<?php
$mac = system('arp -an');
echo $mac;
?>
you will get the output of linux arp -an command.

Use this class (https://github.com/BlakeGardner/php-mac-address)
This is a PHP class for MAC address manipulation on top of Unix, Linux and Mac OS X operating systems. it was primarily written to help with spoofing for wireless security audits.

In windows, If the user is using your script locally, it will be very simple :
<?php
// get all the informations about the client's network
$ipconfig = shell_exec ("ipconfig/all"));
// display those informations
echo $ipconfig;
/*
look for the value of "physical adress" and use substr() function to
retrieve the adress from this long string.
here in my case i'm using a french cmd.
you can change the numbers according adress mac position in the string.
*/
echo substr(shell_exec ("ipconfig/all"),1821,18);
?>

You can get MAC Address or Physical Address using this code
$d = explode('Physical Address. . . . . . . . .',shell_exec ("ipconfig/all"));
$d1 = explode(':',$d[1]);
$d2 = explode(' ',$d1[1]);
return $d2[1];
I used explode many time because shell_exec ("ipconfig/all") return complete detail of all network. so you have to split one by one.
when you run this code then you will get
your MAC Address 00-##-##-CV-12 //this is fake address for show only.

You can use the following solution to solve your problem:
$mac='UNKNOWN';
foreach(explode("\n",str_replace(' ','',trim(`getmac`,"\n"))) as $i)
if(strpos($i,'Tcpip')>-1){$mac=substr($i,0,17);break;}
echo $mac;

Perhaps getting the Mac address is not the best approach for verifying a client's machine over the internet. Consider using a token instead which is stored in the client's browser by an administrator's login.
Therefore the client can only have this token if the administrator grants it to them through their browser. If the token is not present or valid then the client's machine is invalid.

too late to answer but here is my approach since no one mentioned this here:
why not a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.

This one works for me:
<?php
// PHP code to get the MAC address of Server
$MAC = exec('getmac');
// Storing 'getmac' value in $MAC
$MAC = strtok($MAC, ' ');
// Updating $MAC value using strtok function,
// strtok is used to split the string into tokens
// split character of strtok is defined as a space
// because getmac returns transport name after
// MAC address
echo "MAC address of Server is: $MAC";
?>
Source: https://www.geeksforgeeks.org/how-to-get-the-mac-and-ip-address-of-a-connected-client-in-php/

Getting MAC Address Using PHP
Here's the Code:
<?php
$mac = shell_exec("ip link | awk '{print $2}'");
preg_match_all('/([a-z0-9]+):\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})/i', $mac, $matches);
$output = array_combine($matches[1], $matches[2]);
$mac_address_values = json_encode($output, JSON_PRETTY_PRINT);
echo $mac_address_values
?>
Output:
{
"lo": "00:00:00:00:00:00",
"enp0s25": "00:21:cc:d4:2a:23",
"wlp3s0": "84:3a:4b:03:3c:3a",
"wwp0s20u4": "7a:e3:2a:de:66:09"
}

We can get MAC address in Ubuntu by this ways in php
$ipconfig = shell_exec ("ifconfig -a | grep -Po 'HWaddr \K.*$'");
// display mac address
echo $ipconfig;

// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');
// Capture the output into a variable
$mycomsys=ob_get_contents();
// Clean (erase) the output buffer
ob_clean();
$find_mac = "Physical";
//find the "Physical" & Find the position of Physical text
$pmac = strpos($mycomsys, $find_mac);
// Get Physical Address
$macaddress=substr($mycomsys,($pmac+36),17);
//Display Mac Address
echo $macaddress;
This works for me on Windows, as ipconfig /all is Windows system command.

under linux using iptables you can log to a file each request to web server with mac address and ip.
from php lookup last item with ip address and get mac address.
As stated remember that the mac address is from last router on the trace.

You can do this easily using openWRT. If yo use a captive portal you can mix php and openWRT and make a relation between the IP and the mac.
You can write a simple PHP code using:
$localIP = getHostByName(getHostName());
Later, using openWRT you can go to /tmp/dhcp.leases, you will get something with the form:
e4:a7:a0:29:xx:xx 10.239.3.XXX DESKTOP-XXX
There, you have the mac, the IP address and the hostname.

Related

How to get mac address of devices who open my website using php [duplicate]

I need to know the MAC and the IP address of the connect clients, how can I do this in PHP?
Server IP
You can get the server IP address from $_SERVER['SERVER_ADDR'].
Server MAC address
For the MAC address, you could parse the output of netstat -ie in Linux, or ipconfig /all in Windows.
Client IP address
You can get the client IP from $_SERVER['REMOTE_ADDR']
Client MAC address
The client MAC address will not be available to you except in one special circumstance: if the client is on the same ethernet segment as the server.
So, if you are building some kind of LAN based system and your clients are on the same ethernet segment, then you could get the MAC address by parsing the output of arp -n (linux) or arp -a (windows).
Edit: you ask in comments how to get the output of an external command - one way is to use backticks, e.g.
$ipAddress=$_SERVER['REMOTE_ADDR'];
$macAddr=false;
#run the external command, break output into lines
$arp=`arp -a $ipAddress`;
$lines=explode("\n", $arp);
#look for the output line describing our IP address
foreach($lines as $line)
{
$cols=preg_split('/\s+/', trim($line));
if ($cols[0]==$ipAddress)
{
$macAddr=$cols[1];
}
}
But what if the client isn't on a LAN?
Well, you're out of luck unless you can have the client volunteer that information and transmit via other means.
The MAC address of a client (in the sense of the computer that issued the HTTP request) is overwritten by every router between the client and the server.
Client IP is conveniently provided to the script in $_SERVER['REMOTE_ADDR']. In some scenarios, particularly if your web server is behind a proxy (i.e. a caching proxy) $_SERVER['REMOTE ADDR'] will return the IP of the proxy, and there will be an extra value, often $_SERVER['HTTP_X_FORWARDED_FOR'], that contains the IP of the original request client.
Sometimes, particularly when you're dealing with an anonymizing proxy that you don't control, the proxy won't return the real IP address, and all you can hope for is the IP address of the proxy.
I don't think you can get MAC address in PHP, but you can get IP from $_SERVER['REMOTE_ADDR'] variable.
For windows server I think u can use this:
<?php
echo exec('getmac');
?>
All you need to do is to put arp into diferrent group.
Default:
-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*
With command:
sudo chown root:www-data /usr/sbin/arp
you will get:
-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*
And because apache is a daemon running under the user www-data, it's now able to execute this command.
So if you now use a PHP script, e.g.:
<?php
$mac = system('arp -an');
echo $mac;
?>
you will get the output of linux arp -an command.
Use this class (https://github.com/BlakeGardner/php-mac-address)
This is a PHP class for MAC address manipulation on top of Unix, Linux and Mac OS X operating systems. it was primarily written to help with spoofing for wireless security audits.
In windows, If the user is using your script locally, it will be very simple :
<?php
// get all the informations about the client's network
$ipconfig = shell_exec ("ipconfig/all"));
// display those informations
echo $ipconfig;
/*
look for the value of "physical adress" and use substr() function to
retrieve the adress from this long string.
here in my case i'm using a french cmd.
you can change the numbers according adress mac position in the string.
*/
echo substr(shell_exec ("ipconfig/all"),1821,18);
?>
You can get MAC Address or Physical Address using this code
$d = explode('Physical Address. . . . . . . . .',shell_exec ("ipconfig/all"));
$d1 = explode(':',$d[1]);
$d2 = explode(' ',$d1[1]);
return $d2[1];
I used explode many time because shell_exec ("ipconfig/all") return complete detail of all network. so you have to split one by one.
when you run this code then you will get
your MAC Address 00-##-##-CV-12 //this is fake address for show only.
You can use the following solution to solve your problem:
$mac='UNKNOWN';
foreach(explode("\n",str_replace(' ','',trim(`getmac`,"\n"))) as $i)
if(strpos($i,'Tcpip')>-1){$mac=substr($i,0,17);break;}
echo $mac;
Perhaps getting the Mac address is not the best approach for verifying a client's machine over the internet. Consider using a token instead which is stored in the client's browser by an administrator's login.
Therefore the client can only have this token if the administrator grants it to them through their browser. If the token is not present or valid then the client's machine is invalid.
too late to answer but here is my approach since no one mentioned this here:
why not a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.
This one works for me:
<?php
// PHP code to get the MAC address of Server
$MAC = exec('getmac');
// Storing 'getmac' value in $MAC
$MAC = strtok($MAC, ' ');
// Updating $MAC value using strtok function,
// strtok is used to split the string into tokens
// split character of strtok is defined as a space
// because getmac returns transport name after
// MAC address
echo "MAC address of Server is: $MAC";
?>
Source: https://www.geeksforgeeks.org/how-to-get-the-mac-and-ip-address-of-a-connected-client-in-php/
Getting MAC Address Using PHP
Here's the Code:
<?php
$mac = shell_exec("ip link | awk '{print $2}'");
preg_match_all('/([a-z0-9]+):\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})/i', $mac, $matches);
$output = array_combine($matches[1], $matches[2]);
$mac_address_values = json_encode($output, JSON_PRETTY_PRINT);
echo $mac_address_values
?>
Output:
{
"lo": "00:00:00:00:00:00",
"enp0s25": "00:21:cc:d4:2a:23",
"wlp3s0": "84:3a:4b:03:3c:3a",
"wwp0s20u4": "7a:e3:2a:de:66:09"
}
We can get MAC address in Ubuntu by this ways in php
$ipconfig = shell_exec ("ifconfig -a | grep -Po 'HWaddr \K.*$'");
// display mac address
echo $ipconfig;
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');
// Capture the output into a variable
$mycomsys=ob_get_contents();
// Clean (erase) the output buffer
ob_clean();
$find_mac = "Physical";
//find the "Physical" & Find the position of Physical text
$pmac = strpos($mycomsys, $find_mac);
// Get Physical Address
$macaddress=substr($mycomsys,($pmac+36),17);
//Display Mac Address
echo $macaddress;
This works for me on Windows, as ipconfig /all is Windows system command.
under linux using iptables you can log to a file each request to web server with mac address and ip.
from php lookup last item with ip address and get mac address.
As stated remember that the mac address is from last router on the trace.
You can do this easily using openWRT. If yo use a captive portal you can mix php and openWRT and make a relation between the IP and the mac.
You can write a simple PHP code using:
$localIP = getHostByName(getHostName());
Later, using openWRT you can go to /tmp/dhcp.leases, you will get something with the form:
e4:a7:a0:29:xx:xx 10.239.3.XXX DESKTOP-XXX
There, you have the mac, the IP address and the hostname.

Not able to get MAC address of client machine using php [duplicate]

I need to know the MAC and the IP address of the connect clients, how can I do this in PHP?
Server IP
You can get the server IP address from $_SERVER['SERVER_ADDR'].
Server MAC address
For the MAC address, you could parse the output of netstat -ie in Linux, or ipconfig /all in Windows.
Client IP address
You can get the client IP from $_SERVER['REMOTE_ADDR']
Client MAC address
The client MAC address will not be available to you except in one special circumstance: if the client is on the same ethernet segment as the server.
So, if you are building some kind of LAN based system and your clients are on the same ethernet segment, then you could get the MAC address by parsing the output of arp -n (linux) or arp -a (windows).
Edit: you ask in comments how to get the output of an external command - one way is to use backticks, e.g.
$ipAddress=$_SERVER['REMOTE_ADDR'];
$macAddr=false;
#run the external command, break output into lines
$arp=`arp -a $ipAddress`;
$lines=explode("\n", $arp);
#look for the output line describing our IP address
foreach($lines as $line)
{
$cols=preg_split('/\s+/', trim($line));
if ($cols[0]==$ipAddress)
{
$macAddr=$cols[1];
}
}
But what if the client isn't on a LAN?
Well, you're out of luck unless you can have the client volunteer that information and transmit via other means.
The MAC address of a client (in the sense of the computer that issued the HTTP request) is overwritten by every router between the client and the server.
Client IP is conveniently provided to the script in $_SERVER['REMOTE_ADDR']. In some scenarios, particularly if your web server is behind a proxy (i.e. a caching proxy) $_SERVER['REMOTE ADDR'] will return the IP of the proxy, and there will be an extra value, often $_SERVER['HTTP_X_FORWARDED_FOR'], that contains the IP of the original request client.
Sometimes, particularly when you're dealing with an anonymizing proxy that you don't control, the proxy won't return the real IP address, and all you can hope for is the IP address of the proxy.
I don't think you can get MAC address in PHP, but you can get IP from $_SERVER['REMOTE_ADDR'] variable.
For windows server I think u can use this:
<?php
echo exec('getmac');
?>
All you need to do is to put arp into diferrent group.
Default:
-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*
With command:
sudo chown root:www-data /usr/sbin/arp
you will get:
-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*
And because apache is a daemon running under the user www-data, it's now able to execute this command.
So if you now use a PHP script, e.g.:
<?php
$mac = system('arp -an');
echo $mac;
?>
you will get the output of linux arp -an command.
Use this class (https://github.com/BlakeGardner/php-mac-address)
This is a PHP class for MAC address manipulation on top of Unix, Linux and Mac OS X operating systems. it was primarily written to help with spoofing for wireless security audits.
In windows, If the user is using your script locally, it will be very simple :
<?php
// get all the informations about the client's network
$ipconfig = shell_exec ("ipconfig/all"));
// display those informations
echo $ipconfig;
/*
look for the value of "physical adress" and use substr() function to
retrieve the adress from this long string.
here in my case i'm using a french cmd.
you can change the numbers according adress mac position in the string.
*/
echo substr(shell_exec ("ipconfig/all"),1821,18);
?>
You can get MAC Address or Physical Address using this code
$d = explode('Physical Address. . . . . . . . .',shell_exec ("ipconfig/all"));
$d1 = explode(':',$d[1]);
$d2 = explode(' ',$d1[1]);
return $d2[1];
I used explode many time because shell_exec ("ipconfig/all") return complete detail of all network. so you have to split one by one.
when you run this code then you will get
your MAC Address 00-##-##-CV-12 //this is fake address for show only.
You can use the following solution to solve your problem:
$mac='UNKNOWN';
foreach(explode("\n",str_replace(' ','',trim(`getmac`,"\n"))) as $i)
if(strpos($i,'Tcpip')>-1){$mac=substr($i,0,17);break;}
echo $mac;
Perhaps getting the Mac address is not the best approach for verifying a client's machine over the internet. Consider using a token instead which is stored in the client's browser by an administrator's login.
Therefore the client can only have this token if the administrator grants it to them through their browser. If the token is not present or valid then the client's machine is invalid.
too late to answer but here is my approach since no one mentioned this here:
why not a client side solution ?
a javascript implementation to store the mac in a cookie (you can encrypt it before that)
then each request must include that cookie name, else it will be rejected.
to make this even more fun you can make a server side verification
from the mac address you get the manifacturer (there are plenty of free APIs for this)
then compare it with the user_agent value to see if there was some sort of manipulation:
a mac address of HP + a user agent of Safari = reject request.
This one works for me:
<?php
// PHP code to get the MAC address of Server
$MAC = exec('getmac');
// Storing 'getmac' value in $MAC
$MAC = strtok($MAC, ' ');
// Updating $MAC value using strtok function,
// strtok is used to split the string into tokens
// split character of strtok is defined as a space
// because getmac returns transport name after
// MAC address
echo "MAC address of Server is: $MAC";
?>
Source: https://www.geeksforgeeks.org/how-to-get-the-mac-and-ip-address-of-a-connected-client-in-php/
Getting MAC Address Using PHP
Here's the Code:
<?php
$mac = shell_exec("ip link | awk '{print $2}'");
preg_match_all('/([a-z0-9]+):\s+((?:[0-9a-f]{2}:){5}[0-9a-f]{2})/i', $mac, $matches);
$output = array_combine($matches[1], $matches[2]);
$mac_address_values = json_encode($output, JSON_PRETTY_PRINT);
echo $mac_address_values
?>
Output:
{
"lo": "00:00:00:00:00:00",
"enp0s25": "00:21:cc:d4:2a:23",
"wlp3s0": "84:3a:4b:03:3c:3a",
"wwp0s20u4": "7a:e3:2a:de:66:09"
}
We can get MAC address in Ubuntu by this ways in php
$ipconfig = shell_exec ("ifconfig -a | grep -Po 'HWaddr \K.*$'");
// display mac address
echo $ipconfig;
// Turn on output buffering
ob_start();
//Get the ipconfig details using system commond
system('ipconfig /all');
// Capture the output into a variable
$mycomsys=ob_get_contents();
// Clean (erase) the output buffer
ob_clean();
$find_mac = "Physical";
//find the "Physical" & Find the position of Physical text
$pmac = strpos($mycomsys, $find_mac);
// Get Physical Address
$macaddress=substr($mycomsys,($pmac+36),17);
//Display Mac Address
echo $macaddress;
This works for me on Windows, as ipconfig /all is Windows system command.
under linux using iptables you can log to a file each request to web server with mac address and ip.
from php lookup last item with ip address and get mac address.
As stated remember that the mac address is from last router on the trace.
You can do this easily using openWRT. If yo use a captive portal you can mix php and openWRT and make a relation between the IP and the mac.
You can write a simple PHP code using:
$localIP = getHostByName(getHostName());
Later, using openWRT you can go to /tmp/dhcp.leases, you will get something with the form:
e4:a7:a0:29:xx:xx 10.239.3.XXX DESKTOP-XXX
There, you have the mac, the IP address and the hostname.

How to get Client IP Address and MAC Address in laravel?

I am working on laravel project. I need to access client's IP Address and MAC Address those who access the website.
Is their any way to get both the Addresses.
I've used:
Request::ip();
I got the IP address of client. But how to get MAC address.
Thanks in advance.
Yes You Can Do it
BY DEFAULT PHP HAS A BUILT IN FUNCTION THAT EXECUTES THE COMMAND LINE
COMMANDS
shell_exec
http://php.net/manual/en/function.shell-exec.php
exec
http://php.net/manual/en/function.exec.php
So To get the mac address have written the function
function getMAcAddressExec()
{
return substr(exec('getmac'), 0, 17);
}
echo getMAcAddressExec();
function getMAcAddressShellExec()
{
return substr(shell_exec('getmac'), 159,20);
}
echo getMAcAddressShellExec();
EDITED
add follwowing lines in web.php file in routes folder
Route::get('/getmacshellexec',function()
{
$shellexec = shell_exec('getmac');
dd($shellexec);
}
);
Route::get('/getmacexec',function()
{
$shellexec = exec('getmac');
dd($shellexec);
}
);
And Try the url
yourproject/getmacshellexec
AND
yourproject/getmacexec
And Kindly Comment Below of you get any any output
Server IP
You can get the server IP address from $_SERVER['SERVER_ADDR'].
Server MAC address
For the MAC address, you could parse the output of netstat -ie in Linux, or ipconfig /all in Windows.
Client IP address
You can get the client IP from $_SERVER['REMOTE_ADDR']
Client MAC address
The client MAC address will not be available to you except in one special circumstance: if the client is on the same ethernet segment as the server.
So, if you are building some kind of LAN based system and your clients are on the same ethernet segment, then you could get the MAC address by parsing the output of arp -n (linux) or arp -a (windows).
But what if the client isn't on a LAN?
Well, you're out of luck unless you can have the client volunteer that information and transmit via other means.
The exec() is a function that is used to run an external program in PHP. It returns the last line from the result of the command. To get the MAC address, pass the parameter getmac which returns the MAC address of the client. getmacis a CMD command to get the MAC address.
To get the MAC address, we use exec() function.
$macAddr = exec('getmac');
For getting the IP address we have to include use Illuminate\Http\Request; in the Controller and then add the code of the below pre tag. It will give the AP address of the network.
$ipAddr=\Request::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. 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
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.
Solutions:
hardcode in php (upon installation one should edit this in your scripts)
setup a variable in apache environment so that could be accessed through php (upon installation one should add this to apache's config)
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.
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.
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. =)
You can see all the available information with the command:
print_r($_SERVER, 1);
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..
Try using "ifconfig en1 inet" Command.
print_r(exec("ifconfig en1 inet"));
Output:-
inet 192.168.. netmask 0xffffff00 broadcast 192.168.*.255
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"

How to identify server IP address in PHP

How can I identify the server IP address in PHP?
Like this for the server ip:
$_SERVER['SERVER_ADDR'];
and this for the port
$_SERVER['SERVER_PORT'];
If you are using PHP version 5.3 or higher you can do the following:
$host= gethostname();
$ip = gethostbyname($host);
This works well when you are running a stand-alone script, not running through the web server.
for example:
$_SERVER['SERVER_ADDR']
when your on IIS, try:
$_SERVER['LOCAL_ADDR']
I came to this page looking for a way of getting my own ip address not the one of the remote machine connecting to me.
This will not work for a windows machine.
But in case someone searches for what I was looking for:
#! /usr/bin/php
<?php
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo $my_current_ip;
(Shamelessly adapted from How to I get the primary IP address of the local machine on Linux and OS X?)
Neither of the most up-voted answers will reliably return the server's public address. Generally $_SERVER['SERVER_ADDR'] will be correct, but if you're accessing the server via a VPN it will likely return the internal network address rather than a public address, and even when not on the same network some configurations will will simply be blank or have some other specified value.
Likewise, there are scenarios where $host= gethostname(); $ip = gethostbyname($host); won't return the correct values because it's relying on on both DNS (either internally configured or external records) and the server's hostname settings to extrapolate the server's IP address. Both of these steps are potentially faulty. For instance, if the hostname of the server is formatted like a domain name (i.e. HOSTNAME=yahoo.com) then (at least on my php5.4/Centos6 setup) gethostbyname will skip straight to finding Yahoo.com's address rather than the local server's.
Furthermore, because gethostbyname falls back on public DNS records a testing server with unpublished or incorrect public DNS records (for instance, you're accessing the server by localhost or IP address, or if you're overriding public DNS using your local hosts file) then you'll get back either no IP address (it will just return the hostname) or even worse it will return the wrong address specified in the public DNS records if one exists or if there's a wildcard for the domain.
Depending on the situation, you can also try a third approach by doing something like this:
$external_ip = exec('curl http://ipecho.net/plain; echo');
This has its own flaws (relies on a specific third-party site, and there could be network settings that route outbound connections through a different host or proxy) and like gethostbyname it can be slow. I'm honestly not sure which approach will be correct most often, but the lesson to take to heart is that specific scenarios/configurations will result in incorrect outputs for all of these approaches... so if possible verify that the approach you're using is returning the values you expect.
This is what you could use as an adaptation of the above examples without worrying about curl installed on your server.
<?php
// create a new cURL resource
$ch = curl_init ();
// set URL and other appropriate options
curl_setopt ($ch, CURLOPT_URL, "http://ipecho.net/plain");
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
// grab URL and pass it to the browser
$ip = curl_exec ($ch);
echo "The public ip for this server is: $ip";
// close cURL resource, and free up system resources
curl_close ($ch);
?>
Check the $_SERVER array
echo $_SERVER['SERVER_ADDR'];
The previous answers all give $_SERVER['SERVER_ADDR']. This will not work on some IIS installations. If you want this to work on IIS, then use the following:
$server_ip = gethostbyname($_SERVER['SERVER_NAME']);
If you are using PHP in bash shell you can use:
$server_name=exec('hostname');
Because $_SERVER[] SERVER_ADDR, HTTP_HOST and SERVER_NAME are not set.
I found this to work for me:
GetHostByName("");
Running XAMPP v1.7.1 on Windows 7 running Apache webserver.
Unfortunately it just give my gateway IP address.
I just created a simple script that will bring back the $_SERVER['REMOTE_ADDR'] and $_SERVER['SERVER_ADDR'] in IIS so you don't have to change every variable. Just paste this text in your php file that is included in every page.
/** IIS IP Check **/
if(!$_SERVER['SERVER_ADDR']){ $_SERVER['SERVER_ADDR'] = $_SERVER['LOCAL_ADDR']; }
if(!$_SERVER['REMOTE_ADDR']){ $_SERVER['REMOTE_ADDR'] = $_SERVER['LOCAL_ADDR']; }
$serverIP = $_SERVER["SERVER_ADDR"];
echo "Server IP is: <b>{$serverIP}</b>";
You may have to use $HTTP_SERVER_VARS['server_ADDR'] if you are not getting anything from above answers and if you are using older version of PHP
You can use https://icanhazip.com and since Cloudflare owned this project sometimes it can be even more reliable.
$my_real_ip = file_get_contents('https://icanhazip.com/');
Check the $_SERVER array
echo $_SERVER['SERVER_ADDR'];
Here is one solution when the site is running behind a load-balancer, a reverse proxy server, or a CDN like CloudFront:
$conn = curl_init();
curl_setopt($conn, CURLOPT_URL, 'any.valid.url');
curl_exec($conn);
$WebServerIP = curl_getinfo($conn)['local_ip'];
To accurately get the external IP address, you can call checkip.amazonaws.com, a service provided by Amazon.
$ip = exec("curl https://checkip.amazonaws.com");
As we can see it's such a widespread problem that AWS has created that very tool for the world to use.
I would use that over other similar services, since it's provided by AWS and will probably be around for long.
Like this:
$_SERVER['SERVER_ADDR'];

Categories