11

I am facing an issue with $_SERVER['REMOTE_ADDR'] in PHP It is giving a IPv6 like value even though the server is using IPv4.

Can anyone help me to resolve this issue.

2
  • Are you sure that your server is running on IPv4? Commented Sep 15, 2012 at 9:06
  • 2
    This is because your web server is binding to [::], not 0.0.0.0. Commented Sep 16, 2012 at 10:02

1 Answer 1

30

The server is then accepting connections on an IPv6 socket. Some operating systems can do both IPv4 and IPv6 on an IPv6 socket. When that happens the IPv6 address will look like ::ffff:192.0.2.123 or ::ffff:c000:027b which is the same address but written in hexadecimal.

If you see IPv6 addresses like 2a00:8640:1::224:36ff:feef:1d89 then your webserver really is reachable over IPv6 :-)

Anyway, to convert everything back to a canonical form you can use something like:

// Known prefix
$v4mapped_prefix_hex = '00000000000000000000ffff';

$v4mapped_prefix_bin = hex2bin($v4mapped_prefix_hex); 

// Parse
$addr = $_SERVER['REMOTE_ADDR'];
$addr_bin = inet_pton($addr);
if( $addr_bin === FALSE ) {
  // Unparsable? How did they connect?!?
  die('Invalid IP address');
}

// Check prefix
if( substr($addr_bin, 0, strlen($v4mapped_prefix_bin)) == $v4mapped_prefix_bin) {
  // Strip prefix
  $addr_bin = substr($addr_bin, strlen($v4mapped_prefix_bin));
}

// Convert back to printable address in canonical form
$addr = inet_ntop($addr_bin);

Using this code, when you input one of the following:

::ffff:192.000.002.123
::ffff:192.0.2.123
0000:0000:0000:0000:0000:ffff:c000:027b
::ffff:c000:027b
::ffff:c000:27b
192.000.002.123
192.0.2.123

you always get the canonical IPv4 address 192.0.2.123 as output.

And of course IPv6 addresses get returned as canonical IPv6 addresses: 2a00:8640:0001:0000:0224:36ff:feef:1d89 becomes 2a00:8640:1::224:36ff:feef:1d89 etc.

6
  • Thanks. I will do something to filter the IP.
    – Brijesh
    Commented Sep 17, 2012 at 6:16
  • I tried adding all your examples to my test script, and I never execute the striping of the prefix. Are there too many 0's in your sample code for all your examples? Commented Sep 24, 2012 at 21:43
  • No, all the examples are valid. Can you show your test script? Commented Sep 25, 2012 at 7:13
  • 2
    inet_pton("192.000.002.123") gives a Warning and returns false on PHP 5.3.6-10.
    – qbolec
    Commented Jun 22, 2013 at 9:06
  • qbolec: That is a bug on your platform then... Please go to bugs.php.net and file a bug report so it can get fixed. Commented Jun 23, 2013 at 10:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.