skip to Main Content

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


  1. I am using following code to get the IP of the client … and this is outputting IPv4 for some clients, and IPv6 for some

    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:

    • Expand your system so that it can handle IPv6 addresses as well as IPv4 addresses. This is obviously preferred, since it allows everyone to access it, as IPv6 becomes more widespread.
    • Block people from accessing your site with IPv6. Ideally, you’d do this at the DNS level, by not having an "AAAA" record, which advertises the IPv6 address for people to connect to; that way, users who have the ability to connect with IPv4 will do so. That would need to happen wherever the proxy is configured, because by the time the request gets to your application server it’s too late.
    Login or Signup to reply.
  2. To filter IPv6 addresses (as you have asked), use the filter_var function with the FILTER_FLAG_IPV4 flag for IPv4 addresses and FILTER_FLAG_IPV6 for IPv6 respectively:

    if ( filter_var($client_ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV4) )
        // use legacy filter method
    } elseif ( filter_var($client_ip, FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) )
        // use new module for white-listing IPv6 addresses
    }
    

    Here’s the PHP documentation on filters. I hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search