PHP $ _SERVER ['REMOTE_ADDR'] shows IPv6

I ran into a problem with $ _SERVER ['REMOTE_ADDR'] in PHP. It gives IPv6 value, even if the server uses IPv4 protocol.

Can someone help me solve this problem.

+5
php ipv6
source share
1 answer

The server then accepts the connections in the IPv6 slot. Some operating systems can run both IPv4 and IPv6 in the IPv6 slot. When this 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 format.

If you see IPv6 addresses, such as 2a00:8640:1::224:36ff:feef:1d89 , your web server is really accessible via IPv6 2a00:8640:1::224:36ff:feef:1d89

In any case, to convert everything to canonical form, you can use something like:

 // Known prefix $v4mapped_prefix_hex = '00000000000000000000ffff'; $v4mapped_prefix_bin = pack("H*", $v4mapped_prefix_hex); // Or more readable when using PHP >= 5.4 # $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 enter one of the following values:

 ::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 are returned as canonical IPv6 addresses: 2a00:8640:0001:0000:0224:36ff:feef:1d89 becomes 2a00:8640:1::224:36ff:feef:1d89 , etc.

+15
source share

All Articles