Converting IPv6 to IPv4 address in PHP

Viewed 10604

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.

2 Answers

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 {
}

?>
Related