I’m trying to get my ip address.
Here is the code, the getClientIp() method uses a $_SERVER['REMOTE_ADDR'] global variable internally, so $request->getClientIp() and $_SERVER['REMOTE_ADDR'] are the same.
<?php
use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();
Http::response('IP address:' . $request->getClientIp())->json();
I have php deployed in docker on my local machine. So I send a request to localhost
http://localhost/api/v1/ip_address
and get a response.
{
"message": "IP address:172.ХХ.Х.Х", // I replaced my ip numbers with x.
"data": []
}
But there is a problem, the ip address that I get is different from the ip address that applications like "get my ip" give me.
You can just open Google and type in the search "find out my ip online" or "what is my ip" and they will give the correct ip, but the ip that I get from php is not.
I think this is due to the fact that I am making a request to my own computer, and not to a remote server. Can anyone explain why this is happening and if I can get around it?
Update:
From php I get the internal ip address because it starts with 172.X.X…
>Solution :
Your PHP app has no clue about your public IP as it is in the private network. Public IP is assigned to you by your ISP/Router. Router NATs the private IPs so only 1 IP is allocated to your private network.
"What is my IP" website is in the public internet, so it sees your public IP and it has no clue about your 172.xxx.xxx.xxx IP. Router takes care of the translation.
So, from within the app, you will always get your private IP.
If from within your app, you need to know your public IP for what ever reason, you may call the API provided by ipify.org.
curl 'https://api.ipify.org?format=json'
For more details on how NAT works
Reference:
https://www.geeksforgeeks.org/network-address-translation-nat/
