'Converting IPv6 to IPv4 address in PHP

I need to convert IPv6 addresses to IPv4 addresses. To do this, I used code from pedmillon's answer to a related question:

$ipv6 = $_SERVER['REMOTE_ADDR'];
$ipv4 = hexdec(substr($ipv6, 0, 2)). "." . hexdec(substr($ipv6, 2, 2)). "." . hexdec(substr($ipv6, 5, 2)). "." . hexdec(substr($ipv6, 7, 2));

I tried it in my localhost and ::1 gets converted to 0.1.0.0. Is this code correctly working?

I believe it should be showing 127.0.0.1 instead of 0.1.0.0.



Solution 1:[1]

IPv4 and IPv6 are two entirely different mutually incompatible network addressing schemes. There is no way to "translate" from one into the other. An IPv4 address does not correspond to a particular IPv6 address or vice versa. The large majority of nodes on the internet still use IPv4 addresses exclusively at this point, some small percentage run a dual-stack of IPv4 and IPv6 simultaneously, and a vanishingly small number may be IPv6 exclusively. IPv4 and IPv6 nodes cannot talk to one another directly. In the long run everyone should be moving to IPv6 exclusively, but that's a long way off.

can you explain how can I use IPv6 address to block countries

The same way you block specific regions using IPv4: get a database that maps IPs to geographic locations. The only difference is that you need to find a database or service which does that for IPv6 addresses.

Solution 2:[2]

As mentioned above - IPV6 and IPv4 are completely different addressing systems, one does not convert from one to another. However if you look at the issue another way you should be able to get the IPV4 address that may be used by the client. I used PHP and JavaScript to achieve this. Here is my sample code - it works for me. Your output will look something like this:

IP Address: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx IPv4:

xx.xx.xxx.xxx

<? // Grab the IP address of the user
$ipaddress = getenv("REMOTE_ADDR") ; echo 'IP Address: '.$ipaddress;

// Check if we need to try and get the IPv4 address
if(filter_var($ipaddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
?>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
    </script>

      <script>

    /* Add "https://api.ipify.org?format=json" statement
               this will communicate with the ipify servers in
               order to retrieve the IP address $.getJSON will
               load JSON-encoded data from the server using a
               GET HTTP request */

    $.getJSON("https://api.ipify.org?format=json", function(data) {

        // Setting text of element P with id gfg
        $("#gfg").html(data.ip);
    })
    </script>

       <p id="gfg"></p>
<?
}
else {
}

?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 deceze
Solution 2 Benton Smith