简体   繁体   中英

PHP : Matching an IP in a range between? (IPv4 and IPv6)

Is it a good idea to use inet_pton() function to match an IP in a specific range? And is it good to use it for both IPv4 and IPv6 ?

For example:

$start = inet_pton('192.168.0.1');
$end = inet_pton('195.200.0.200');
$ip = inet_pton($_SERVER['REMOTE_ADDR']);

if($ip >= $start && $ip <= $end) {
       echo 'in range';
}
else {
echo 'not in range';
}

Use PHP's ip2long function. It will convert IPv4 to numbers.

Try this code:-

$start = ip2long('192.168.0.1');
$end = ip2long('195.200.0.200');
$ip = ip2long($_SERVER['REMOTE_ADDR']);

For both IPv4 and IPv6 addresses use this function for global use.

function ipaddress_to_ipnumber($ipaddress) {
    $pton = @inet_pton($ipaddress);
    if (!$pton) { return false; }
    $number = '';
    foreach (unpack('C*', $pton) as $byte) {
        $number .= str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
    }
    return base_convert(ltrim($number, '0'), 2, 10);
  }

$start = ipaddress_to_ipnumber("192.168.178.255");
$end = ipaddress_to_ipnumber('195.200.0.200');
$ip = ipaddress_to_ipnumber($_SERVER['REMOTE_ADDR']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM