I have trouble getting IPv4 Address, as IPv6 seems automatically preferred.
However, this is very difficult, as my IP Whitelist system uses solely IPv4.
I am using following code to get the IP of the client:
$client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
And this is outputting IPv4 for some clients, and IPv6 for some, however, most of the clients are registered with IPv6, and currently, none of my codebase supports a system for IPv6, therefore this causes stupid bugs and errors, since there is a whitelist system which only takes in IPv4.
How can i filter IPv6, so that the code only assembles IPv4 and not v6?
Also, the server is behind a HTTP/HTTPS Proxy, therefore i need to use forwarded header.
2
Answers
The code is doing the same thing for all clients: outputting the IP address they connected from. If someone connects using IPv6, that’s the only address you can get.
Imagine you have a system that assumes everyone will have a postal address in Norway. Then someone signs up with an address in the UK; there’s no point trying to find a Norwegian address for them, they don’t have one. Either you change the system to handle UK addresses, or you block them from signing up.
You have the same two options here:
To filter IPv6 addresses (as you have asked), use the
filter_var
function with theFILTER_FLAG_IPV4
flag for IPv4 addresses andFILTER_FLAG_IPV6
for IPv6 respectively:Here’s the PHP documentation on filters. I hope it helps.