How to make a page to know IPv6?

3

To know IPv4 I can use the code on a page:

<?php
    echo $_SERVER["REMOTE_ADDR"];
?>

But I can not find anything similar to do the same with IPv6, which appears to me a lot is already sites with converters.

Even though there is no code like the one above for IPv6, I would love to be able to do one that fixes the conversion automatically for IPv6.

And the end result is for example 2002:55F6:9A82:0:0:0:0:0 as you can see in link

    
asked by anonymous 29.09.2014 / 16:28

1 answer

8

What defines the address is the connection

The $_SERVER["REMOTE_ADDR"]; variable shows both IPv4 and IPv6. It only depends on how the server's network is configured, and how the client accessed your page.

If the machine is serving an IPv4 address you will get something like:

208.67.222.222

If you're serving on IPv6, you'll already have something on this line:

2001:0db8:85a3:08d3:1319:8a2e:0370:7344


  

Edit in response to a comment: If you already have a server that catches IPv6, just force the IPv6 request to your server to see the REMOTE_ADDR working in practice. For example, putting IPv6 in href of a link, or in the URL of a iframe or request ajax if you prefer. Nothing prevents you from testing both IPv4 and IPv6 on the same page, but you need to do both requests separately.


To standardize storage

PHP has the function inet_pton() , which understands both ways, and converts the address for a binary compact version.

Just to illustrate, I did a small function that converts any valid IP into long IPv6:

<?php
   function normalizeIP( $ip ) {
      $ip = inet_pton( $ip );
      if( strlen( $ip ) < 5 ) {
         $ip = chr( 255 ).chr( 255 ).str_pad( $ip, 4, chr( 0 ), STR_PAD_LEFT );
      }
      $ip = str_split( str_pad( $ip, 16, chr( 0 ), STR_PAD_LEFT ) );
      $out = '';
      for( $i = 0; $i < 16; ) {
         if( $i && $i % 2 == 0 ) $out .= ':';
         $out .= str_pad( dechex( ord( $ip[$i++] ) ), 2, '0', STR_PAD_LEFT );
      }
      return $out;
   }
?>

See IDEONE .

Of course in practice you probably will not need any of this, just store the result of inet_pton() in a field that accepts binary strings of variable length up to 16 characters.


In brief

This depends only on the configuration of the server connection, and even if the machine meets the two protocols, it can happen that the client A is using IPv4, and a client B per IPv6. Both will have the respective IP being stored in $_SERVER["REMOTE_ADDR"] .

If you have both protocols enabled on the server , it may be that IPv4 is converted to an IPv6 notation and you have these results (note the prefix ::ffff indicating that this is an IPv4 in IPv6 format):

::ffff:192.000.002.124
::ffff:192.0.2.124
0000:0000:0000:0000:0000:ffff:c000:027c
::ffff:c000:027c
::ffff:c000:27c

All the above addresses are equivalent to IPv4 192.0.2.124 .

    
29.09.2014 / 17:29