How to know which version of the Internet Protocol (IP) a client is using when connecting to my server?

后端 未结 7 473
北海茫月
北海茫月 2020-12-04 19:38

I want to check via php if someone connects to my site via IPv4 or IPv6.

The client address can be found in $_SERVER[\"REMOTE_ADDR\"] but

相关标签:
7条回答
  • 2020-12-04 20:04

    You can use this:

    function ipVersion($txt) {
         return strpos($txt, ":") === false ? 4 : 6;
    }
    
    0 讨论(0)
  • 2020-12-04 20:08

    What about counting the number of '.' and/or ':' in $_SERVER["REMOTE_ADDR"] ?

    If there is more than 0 ':', and no '.' symbol in $_SERVER["REMOTE_ADDR"], I suppose you can consider you user is connected via IPv6.


    Another solution might be to use the filter extension : there are constants (see the end of the page) that seem to be related to IPv4 and IPv6 :

    FILTER_FLAG_IPV4 (integer)
    Allow only IPv4 address in "validate_ip" filter.

    FILTER_FLAG_IPV6 (integer)
    Allow only IPv6 address in "validate_ip" filter.

    0 讨论(0)
  • 2020-12-04 20:10

    You can use AF_INET6 to detect if PHP is compiled with IPv6 support:

    <?php
    if ( defined('AF_INET6') ) {
        echo 'Yes';
    } else {
        echo 'No';
    }
    ?>
    
    0 讨论(0)
  • 2020-12-04 20:20

    You can use inet_pton:

    <?php
    
    $packedIp = @inet_pton($ip);
    
    if ($packedIp === false) {
        // invalid IP
    } else if (isset($packedIp[4])) {
        // IPv6
    } else {
        // IPv4
    }
    
    0 讨论(0)
  • 2020-12-04 20:20

    IPv4 addresses all match the regex /^\d{1,3}(\.\d{1,3}){3,3}$/.

    0 讨论(0)
  • 2020-12-04 20:22

    Check for IPv4

    $ip = "255.255.255.255";
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {    
        echo "Valid IPv4";
    }
    else {
        echo "Invalid IPv4";
    }
    

    Check for IPv6

    $ip = "FE80:0000:0000:0000:0202:B3FF:FE1E:8329";    
    if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        echo "Valid IPv6";
    }
    else {
        echo "Invalid IPv6";
    }
    

    For more, check PHP function filter_vars and list of filters for validation.

    0 讨论(0)
提交回复
热议问题