How to identify server IP address in PHP - 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'];

Related

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.

IP failover in cURL - is it possible?

I have VPS on OVH, and I have one failover IP (eth0:0). Could you tell me, if It is possible to use this failover IP in cURL requests with PHP?
I tried:
curl_setopt($ch, CURLOPT_INTERFACE, "eth0:0");
and:
curl_setopt($ch, CURLOPT_INTERFACE, "XX.XXX.XXX.XXX");
..but it doesn't work :-/
Since I can't comment, I will try to help you here.
Can you try the following command and see if you get the correct results?
curl --interface eth0 http://ifconfig.me
curl --interface eth0:0 http://ifconfig.me
Check if the first one returns the correct IP for the device eth0, and the second one the correct IP for the device eth0:0.
The reason I am asking that is to try to figure out if the problem is with curl or on the OS (routing tables, etc).

Equivalent of iframe on server side

Is there any way to create an "iframe-like" on server side ? The fact is, I need to acceed to certains page of my society's intranet from our website's administration part.
I already have a SQL link to the database that works fine, but here I would access to the pages without duplicating the source code on the webserver.
My infrasructure is the following:
The Webserver is in a DMZ and has the following local IP: 192.168.63.10.
Our Intranet server is NOT in the DMZ and has the following IP: 192.168.1.20.
Our Firewall has serverals rules and I've just added the following:
DMZ->LAN Allow HTTP/HTTPS traffic and LAN->DMZ Allow HTTP/HTTPS (just as we've done for the SQL redirection)
I've tried the following PHP function:
$ch = curl_init();
// set URL and other appropriate options (also tried with IP adress instead of domain)
curl_setopt($ch, CURLOPT_URL, "http://intranet.socname.ch/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
I've also tried:
$page = file_get_contents('http://192.168.1.20/');
echo $page;
Or:
header('Location:http://192.168.1.20');
But in all thoses cases, it works fine from local but not from internet. From internet, it doesn't load and after a while, says that the server isn't responding.
Thanks for your help !
Your first and second solution could work. Can your webserver access 192.168.1.20? (try ping 192.168.1.20 on your webserver) or resolve the Hostname intranet.socname.ch ? (try nslookup intranet.socname.ch)
What you're looking for is called "proxy", here is a simple PHP project that I found:
https://github.com/Alexxz/Simple-php-proxy-script
Download the repo, copy example.simple-php-proxy_config.php to simple-php-proxy_config.php and change $dest_host = "intranet.socname.ch";
It should do the trick! (may also need to change $proxy_base_url)

Is there a way to check if a host is up?

I'm trying to do this in PHP. I need to check if a specified host is "up"
I thought of pinging the specified host (though I'm not sure how I would, since that would require root. --help here?)
I also though of using fsockopen() to try to connect on a specified port, but that would fail too, if the host wasn't listening for connections on that port.
Additionally, some hosts block ping requests, so how might I get around this? This part isn't a necessity, though, so don't worry about this too much. I realize this one might get tricky.
I typically do a simple cURL for a public page and see if it returns a 200. If you get a 500, 404, or anything besides a 200 response you know something fishy is up.
The short answer is that there is no good, universal way to do this. Ping is about as close as you can get (almost all hosts will respond to that), but as you observed, in PHP that usually requires root access to use the low port.
Does your host allow you to execute system calls, so you could run the ping command at the OS level and then parse the results? This is probably your best bet.
$result = exec("ping -c 2 google.com");
If a host is blocking a ping request, you could do a more general portscan to look for other open ports (but this is pretty rude, don't do it to hosts who haven't given you specific permission). Nmap is a good tool for doing this. It uses quite a few tricks to figure out if a host is up and what services may or may not be running. Be careful though, as some shared hosting providers will terminate your account for "hacking activity" if you install and use Nmap, especially against hosts you do not control or have permission to probe.
Beyond that, if you are on the same unswitched ethernet layer as another host (if you happen to be on the same open WiFi network, for example), an ethernet adaptor in promiscuous mode can sniff traffic to and from a host even if it does not respond directly to you.
You could use cURL
$url = 'yoururl';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (200==$retcode) {
// All's well
} else {
// not so much
}
For the host to be monitored at all, at least one port must be open. Is the host a web server? If so you could just open a connection to port 80, as long as it's opened successfully then at least some part of the host is working.
A better solution would be to have a script that is web accessible to just your monitor, and then you could open a connection to that, and that script would return various bits of system info.
EDIT--
How thorough do you want this test to be?
[server on] -> [apache running] -> [web application working]
Are all different levels of working. Just showing apache is returning something does at least show the server is on, but not that your web app is running.
(I realise that you may not be running anything like this but I hope it's a useful example)
EDIT--
Would it be worth installing a lightweight http server (I mean very light weight) just for monitoring?
Failing that could you install something on the hosts that phoned home every so often to show they are up?
I used gethostbyname($hostname).
The function gives you the IP if the host is up, or the input hostname if it couldn't find the IP.
if ($hostname !== gethostbyname($hostname)) {
//Host is up
}

Get the client's computer name

I am getting the client's (website user's) IP address. Now I'd like to go one step further by knowing the user's computer name. So far, my research has not turned up anything to aid me in retrieving this information.
Is it possible to use the user's IP address, or some other means, to get my visitor's computer name using PHP?
PHP 5.4+
gethostbyaddr($_SERVER['REMOTE_ADDR'])
You can perform a reverse DNS lookup using gethostbyaddr().
Note that this will give you the name of the host the request came from according to reverse DNS.
It will not give you a result if reverse DNS isn't set up
It will not give you the Windows name of the computer
It will give you the name of the router if NAT is involved or proxy if a proxy is involved.
Not possible with plain php running on the server. It'd be a security/privacy issue to know details of the client such as computer name, mac address, contents of his drive.
You need some sort of application running on the client's machine in order to get this.
If you're referring to the hostname (displayed for instance by the hostname command on linux) of the computer doing the request:
That information is not included in an HTTP request. (That is, it's impossible for PHP to figure out.)
You could do a reverse DNS lookup, but that's probably not what you want anyway.
This is all that you could get using just PHP (you may try these butIi dont think this is what you actually needed):
gethostname()
gethostbyname(gethostname())
$_SERVER['HTTP_HOST']
$_SERVER['SERVER_SIGNATURE']
$_SERVER['SERVER_NAME']
$_SERVER['SERVER_ADDR']
$_SERVER['SERVER_PORT']
$_SERVER['REMOTE_ADDR']
gethostbyaddr($_SERVER['REMOTE_ADDR'])
php_uname()
The only thing you could do is try to get a DNS name for the client. "Computer Name" is a Windows made-up thing. Just call the built-in function gethostbyaddr() with the client's IP address. However, it won't always (hardly ever) work.
You can do this by
$_SERVER['REMOTE_HOST']
'REMOTE_HOST' - The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.
Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. As David mentioned you can also use . gethostbyaddr()
Pls go thru all the comments in the
url before actually using the
function.
Do something lik this:
<?php
//get host by name
echo gethostname();
echo "<br>";
//get OS
echo php_uname();
?>

Categories