如何检查 IP 地址是否在 PHP 中的两个 IP 范围内


How to check an IP address is within a range of two IPs in PHP?

我有一个IP地址,我得到了另外两个IP地址,它们共同创建了一个IP范围。我想检查第一个 IP 地址是否在此范围内。我怎样才能在 PHP 中找到它?

使用ip2long()可以轻松地将地址转换为数字。在此之后,您只需要检查该数字是否在范围内:

if ($ip <= $high_ip && $low_ip <= $ip) {
  echo "in range";
}

这个网站提供了一个很好的指南和代码来做到这一点(这是谷歌搜索这个问题的第一个结果):

<?php
/*
 * ip_in_range.php - Function to determine if an IP is located in a
 *                   specific range as specified via several alternative
 *                   formats.
 *
 * Network ranges can be specified as:
 * 1. Wildcard format:     1.2.3.*
 * 2. CIDR format:         1.2.3/24  OR  1.2.3.4/255.255.255.0
 * 3. Start-End IP format: 1.2.3.0-1.2.3.255
 *
 * Return value BOOLEAN : ip_in_range($ip, $range);
 *
 * Copyright 2008: Paul Gregg <pgregg@pgregg.com>
 * 10 January 2008
 * Version: 1.2
 *
 * Source website: http://www.pgregg.com/projects/php/ip_in_range/
 * Version 1.2
 *
 * This software is Donationware - if you feel you have benefited from
 * the use of this tool then please consider a donation. The value of
 * which is entirely left up to your discretion.
 * http://www.pgregg.com/donate/
 *
 * Please do not remove this header, or source attibution from this file.
 */

// decbin32
// In order to simplify working with IP addresses (in binary) and their
// netmasks, it is easier to ensure that the binary strings are padded
// with zeros out to 32 characters - IP addresses are 32 bit numbers
Function decbin32 ($dec) {
  return str_pad(decbin($dec), 32, '0', STR_PAD_LEFT);
}
// ip_in_range
// This function takes 2 arguments, an IP address and a "range" in several
// different formats.
// Network ranges can be specified as:
// 1. Wildcard format:     1.2.3.*
// 2. CIDR format:         1.2.3/24  OR  1.2.3.4/255.255.255.0
// 3. Start-End IP format: 1.2.3.0-1.2.3.255
// The function will return true if the supplied IP is within the range.
// Note little validation is done on the range inputs - it expects you to
// use one of the above 3 formats.
Function ip_in_range($ip, $range) {
  if (strpos($range, '/') !== false) {
    // $range is in IP/NETMASK format
    list($range, $netmask) = explode('/', $range, 2);
    if (strpos($netmask, '.') !== false) {
      // $netmask is a 255.255.0.0 format
      $netmask = str_replace('*', '0', $netmask);
      $netmask_dec = ip2long($netmask);
      return ( (ip2long($ip) & $netmask_dec) == (ip2long($range) & $netmask_dec) );
    } else {
      // $netmask is a CIDR size block
      // fix the range argument
      $x = explode('.', $range);
      while(count($x)<4) $x[] = '0';
      list($a,$b,$c,$d) = $x;
      $range = sprintf("%u.%u.%u.%u", empty($a)?'0':$a, empty($b)?'0':$b,empty($c)?'0':$c,empty($d)?'0':$d);
      $range_dec = ip2long($range);
      $ip_dec = ip2long($ip);
      # Strategy 1 - Create the netmask with 'netmask' 1s and then fill it to 32 with 0s
      #$netmask_dec = bindec(str_pad('', $netmask, '1') . str_pad('', 32-$netmask, '0'));
      # Strategy 2 - Use math to create it
      $wildcard_dec = pow(2, (32-$netmask)) - 1;
      $netmask_dec = ~ $wildcard_dec;
      return (($ip_dec & $netmask_dec) == ($range_dec & $netmask_dec));
    }
  } else {
    // range might be 255.255.*.* or 1.2.3.0-1.2.3.255
    if (strpos($range, '*') !==false) { // a.b.*.* format
      // Just convert to A-B format by setting * to 0 for A and 255 for B
      $lower = str_replace('*', '0', $range);
      $upper = str_replace('*', '255', $range);
      $range = "$lower-$upper";
    }
    if (strpos($range, '-')!==false) { // A-B format
      list($lower, $upper) = explode('-', $range, 2);
      $lower_dec = (float)sprintf("%u",ip2long($lower));
      $upper_dec = (float)sprintf("%u",ip2long($upper));
      $ip_dec = (float)sprintf("%u",ip2long($ip));
      return ( ($ip_dec>=$lower_dec) && ($ip_dec<=$upper_dec) );
    }
    echo 'Range argument is not in 1.2.3.4/24 or 1.2.3.4/255.255.255.0 format';
    return false;
  }
}
?>

我找到了这个小要点它的解决方案比这里已经提到的更简单/更短。

第二个参数(范围)可以是静态 ip(如 127.0.0.1)或范围(如 127.0.0.0/24)。

/**
 * Check if a given ip is in a network
 * @param  string $ip    IP to check in IPV4 format eg. 127.0.0.1
 * @param  string $range IP/CIDR netmask eg. 127.0.0.0/24, also 127.0.0.1 is accepted and /32 assumed
 * @return boolean true if the ip is in this range / false if not.
 */
function ip_in_range( $ip, $range ) {
    if ( strpos( $range, '/' ) === false ) {
        $range .= '/32';
    }
    // $range is in IP/CIDR format eg 127.0.0.1/24
    list( $range, $netmask ) = explode( '/', $range, 2 );
    $range_decimal = ip2long( $range );
    $ip_decimal = ip2long( $ip );
    $wildcard_decimal = pow( 2, ( 32 - $netmask ) ) - 1;
    $netmask_decimal = ~ $wildcard_decimal;
    return ( ( $ip_decimal & $netmask_decimal ) == ( $range_decimal & $netmask_decimal ) );
}
if(version_compare($low_ip, $ip) + version_compare($ip, $high_ip) === -2) {
    echo "in range";
}

在范围内比较(包括 IPv6 支持)

PHP 5.1.0 中引入了以下两个函数,inet_ptoninet_pton 。它们的目的是将人类可读的 IP 地址转换为其打包的in_addr表示形式。由于结果不是纯二进制的,因此我们需要使用 unpack 函数来应用按位运算符。

这两个函数都支持 IPv6 和 IPv4。唯一的区别是你如何从结果中解压缩地址。使用 IPv6,您将使用 A16 解压缩内容,使用 IPv4,您将使用 A4 解压缩。

为了将前面的内容放在一个角度来看,这里有一个小的示例输出来帮助澄清:

// Our Example IP's
$ip4= "10.22.99.129";
$ip6= "fe80:1:2:3:a:bad:1dea:dad";

// ip2long examples
var_dump( ip2long($ip4) ); // int(169239425)
var_dump( ip2long($ip6) ); // bool(false)

// inet_pton examples
var_dump( inet_pton( $ip4 ) ); // string(4)
var_dump( inet_pton( $ip6 ) ); // string(16)

我们在上面演示了 inet_* 系列同时支持 IPv6 和 v4。我们的下一步将是将打包结果转换为未打包的变量。

// Unpacking and Packing
$_u4 = current( unpack( "A4", inet_pton( $ip4 ) ) );
var_dump( inet_ntop( pack( "A4", $_u4 ) ) ); // string(12) "10.22.99.129"

$_u6 = current( unpack( "A16", inet_pton( $ip6 ) ) );
var_dump( inet_ntop( pack( "A16", $_u6 ) ) ); //string(25) "fe80:1:2:3:a:bad:1dea:dad"

注意:当前函数返回数组的第一个索引。它等同于说$array[0]。

拆包和包装后,我们可以看到我们取得了与输入相同的结果。这是一个简单的概念证明,以确保我们不会丢失任何数据。

最后使用,

if ($ip <= $high_ip && $low_ip <= $ip) {
  echo "in range";
}

参考: php.net

使用支持 IPv4 和 IPv6 的优秀 rlanvin/php-ip(通过 GMP 扩展):

use PhpIP'IPBlock;
$block = IPBlock::create('10.0.0.0/24');
$block->contains('10.0.0.42'); // true

有关更多示例,请参阅他们的文档。

我总是建议 ip2long,但有时您需要检查网络等。我过去构建了一个IPv4网络类,可以在HighOnPHP上找到。

使用 IP 寻址的好处是它的灵活性,尤其是在使用 BITWISE 运算符时。AND'ing,OR'ing和BitShift将像魅力一样工作。

这是一篇旧帖子,但我在 GitHub 上有一个很好的解决方案。

$ip_in_range = is_ip_in_range('54.208.101.55', array(
    '50.16.241.113'     =>  '50.16.241.117',
    '54.208.100.253'    =>  '54.208.102.37'
)); 

此函数将在不匹配时返回匹配的 IP 或布尔值 false。

这是函数:

// https://github.com/CreativForm/PHP-Solutions/blob/master/function.ip.in.range.php
function is_ip_in_range( $ip, $range ){
    if(!is_array($range)) return false;
    // Let's search first single one
    ksort($range);
    
    // We need numerical representation of the IP
    $ip2long = ip2long($ip);
    
    // Non IP values needs to be removed
    if($ip2long !== false)
    {
        // Let's loop
        foreach($range as $start => $end)
        {
            // Convert to numerical representations as well
            $end = ip2long($end);
            $start = ip2long($start);
            $is_key = ($start === false);
            
            // Remove bad one
            if($end === false) continue;
            
            // Here we looking for single IP does match
            if(is_numeric($start) && $is_key && $end === $ip2long)
            {
                return $ip;
            }
            else
            {
                // And here we have check is in the range
                if(!$is_key && $ip2long >= $start && $ip2long <= $end)
                {
                    return $ip;
                }
            }
        }
    }
    
    // Ok, it's not finded
    return false;
}

顺便说一句,如果您需要一次检查多个范围,您可以在代码中添加几行以传递范围数组。第二个参数可以是数组或字符串:

public static function ip_in_range($ip, $range) {
      if (is_array($range)) {
          foreach ($range as $r) {
              return self::ip_in_range($ip, $r);
          }
      } else {
          if ($ip === $range) { // in case you have passed a static IP, not a range
             return TRUE;
          }
      } 
      // The rest of the code follows here..
      // .........
}

这是我对这个主题的态度。

function validateIP($whitelist, $ip) {
    // e.g ::1
    if($whitelist == $ip) {
        return true;
    }
    // split each part of the IP address and set it to an array
    $validated1 = explode(".", $whitelist);
    $validated2 = explode(".", $ip);
    // check array index to avoid undefined index errors
    if(count($validated1) >= 3 && count($validated2) == 4) {
        // check that each value of the array is identical with our whitelisted IP,
        // except from the last part which doesn't matter
        if($validated1[0] == $validated2[0] && $validated1[1] == $validated2[1] && $validated1[2] == $validated2[2]) {
            return true;
        }   
    }
    return false;
}

我为我的客户使用了这个:

$clientIpArray = explode(".", $clientIp);
$fromArray = explode(".", $from);
$toArray = explode(".", $to);
        
if( ((str_pad($clientIpArray[0], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[0], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[0], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[0], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[1], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[1], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[1], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[1], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[2], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[2], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[2], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[2], 3, "0", STR_PAD_LEFT)))
 &&((str_pad($clientIpArray[3], 3, "0", STR_PAD_LEFT) >= str_pad($fromArray[3], 3, "0", STR_PAD_LEFT)) && (str_pad($clientIpArray[3], 3, "0", STR_PAD_LEFT) <= str_pad($toArray[3], 3, "0", STR_PAD_LEFT)))){
  echo "IP within range";
}

例如,让我们举这个例子:

$clientIp = "120.02.3.112";
$from = "1.02.1.112";
$to = "120.02.20.112";

如您所知,此IP在该范围内。如果您尝试按原样比较它,它将不起作用。我的解决方案是将 IP 划分为元素,例如生成的数组将是:

$clientIpArray = ["120","02","3","112"];
$fromArray = ["1","02","1","112"];
$toArray = ["120","02","20","112"];

我们有 4 个元素要比较,这里我使用str_pad函数从每个元素生成一个 3 个字符的字符串,所以不是检查"3"是否在"1"和"20"之间(这不是真的),我们将检查"003"是否在"001"和"020"之间(这是正确的)。