I'm working on a website, and one of the things I would like to do is display MY IP address to users. The website is made with CodeIgniter, so I was looking to find my server IP with PHP. The IP address may change (it's a roamer), so I'd like to find it dynamically, not just hard code it. I tried this:
$data['hostname'] = NULL; $data['ip'] = NULL; $var = gethostname(); if ($var === FALSE) { $var = NULL; } else { $data['hostname'] = $var; $data['ip'] = gethostbyname($var); }
However, instead of giving me the Hostname and the IP, I got: "Moria" and "127.0.1.1". Not quite what I am looking for. Rather, it should say "Moria.student.rit.edu" for the Hostname, and the IP address. Any help?
In order to obtain the IP address of the server one can use ['SERVER_ADDR'], it returns the IP address of the server under the current script is executing. Another method is using the ['REMOTE_ADDR'] in the $_SERVER array.
$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page. $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page. $_SERVER['REMOTE_PORT']
You can try this one also. $ip=$_SERVER['REMOTE_ADDR']; echo "IP address= $ip"; If your application hosted on same machine from where you are trying to request it will always return '::1', It means LocalHost. else it will return client IP Address.
The simplest way to get the visitor's/client's IP address is using the $_SERVER['REMOTE_ADDR'] or $_SERVER['REMOTE_HOST'] variables. However, sometimes this does not return the correct IP address of the visitor, so we can use some other server variables to get the IP address.
Try $_SERVER['SERVER_ADDR']
. It will be the IP address that the server is listening on. You can use DNS functions (e.g., gethostbyaddr()
) to get the host name.
See http://www.php.net/manual/en/reserved.variables.server.php.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With