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

65

我有一个IP地址,另外还有两个IP地址,它们共同构成了一个IP范围。我想检查第一个IP地址是否在这个范围内。在PHP中,我该如何找出答案?


9
+1 表示顶起此问题,使其得以回到0分。我不明白为什么它会被踩。 - Hubro
4
由于缺乏研究努力。 - CodeCaster
2
你怎么知道在提问之前进行了多少研究?对我来说,你对这个问题的问题是它太简短了。但在他更好地定义“范围”之前,我将取消我的点赞。 - Hubro
3
我是女性,好的范围是在从abc.def.ghi.jkl到mno.pqr.stu.vwx之间。 - guitarlass
2
我昨天大部分时间都在寻找关于“范围”、“缩放”、“图表”的一些具体答案……看看你能找到什么,告诉我有多少描述了highcharts的默认设置。当你不知道答案时,在谷歌中使用正确的术语可能是一项非常枯燥无味的任务。我至少花费了2个小时搜索,然后才会提问,通常会得到带有正确“关键词”的答案,然后可以梦想中获得关于该主题的每一个具体答案。 - GDP
显示剩余6条评论
11个回答

76

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

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

为什么IP地址写成x.x.x.xxx而不是普通数字? - Maciek Semik
6
因为对于人类来说,这样更易于阅读、书写和记忆。 - Carsten
3
即使有44个赞同票以及批准的答案,当存在一个致命的bug时,这段代码仍然会失败。测试用例失败:$high_ip = ip2long('129.255.255.255'); $low_ip = ip2long('127.0.0.0'); $ip = ip2long('127.3.4.5'); if ($ip <= $high_ip && $low_ip <= $ip) { echo "$ip is in range of $low_ip to $high_ip"; } else { echo "$ip is NOT in range of $low_ip to $high_ip"; } 输出结果为:2130904069 is NOT in range of 2130706432 to -2113929217,这应该能让您明白为什么ip2long()函数不能正常工作。 - Rick James
1
@RickJames 我在 PHP 沙盒中尝试了一下,它似乎可以在 PHP 4.4 到 7 的版本上运行 :) 你用的是哪个 PHP 版本? - Almouro
1
我正在查看 PHP_VERSION=5.4.12 PHP_INT_MAX=2147483647 PHP_INT_SIZE=4 - Rick James
6
@Rick James的问题是由于32位系统上整数大小限制导致的,该值会“绕回”成一个负数。这篇回答并不适用于32位系统。在32位系统上的解决方法是在进行比较之前,将返回的值通过sprintf转换为无符号整数,请参阅https://dev59.com/b3A75IYBdhLWcg3w3NHf。 - siliconrockstar

37

这个网站提供了一个很棒的指南和代码,可以用它来判断IP地址是否在特定范围内(这是在Google搜索此问题的第一个结果):

<?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;
  }

}
?>

你是否有这个答案的另一个链接?这里的链接已经失效了。 - Taryn
很遗憾,不是这样的。希望这里的代码能够自己解释清楚。 - John Conde
1
我已经用互联网档案馆的版本替换了它。 - Taryn
他们真棒。感谢你找到它。 - John Conde
谢谢,这真的很方便。 - Vlado
我已经使用这段代码一段时间了,它非常好用,但是当IP地址格式不正确时会出现一些问题。对于范围而言,ip2long部分可能会返回0并且破坏比较。 例如:ip_in_range('1.1.1.1', '1.2.03.0-1.2.3.255') 返回True。 - ruizfrontend

17

我发现这个小的Gist比这里已经提到的解决方案更简单/更短。

第二个参数(范围)可以是静态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 ) );
}

10
== false改为=== false,当字符串的第一个字符是匹配字符时strpos()函数会返回0,而在PHP中0等于false。===可以比较类型。 - e-info128

10
if(version_compare($low_ip, $ip) + version_compare($ip, $high_ip) === -2) {
    echo "in range";
}

2
仅适用于IPv4,但很好 :) - Pyton
终于有人欣赏它了,这么长时间以来我一直认为它相当聪明 ;) - Bas
1
太棒了!像魔法一样好用! - Björn C

6

区间比较(包括 IPv6 支持)

以下两个函数在 PHP 5.1.0 中引入:inet_ptoninet_ntop。它们的目的是将人类可读的 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";
}

Reference: php.net


你好,以下是翻译内容:“对我似乎不起作用,在哪个点你会执行比较?” - Karl Adler
2
为什么这个答案会有一个踩?实际上,它比其他答案更好。 - Hossein Shahdoost

5
使用优秀的rlanvin/php-ip,该工具支持IPv4和IPv6(通过GMP扩展)。
use PhpIP\IPBlock;

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

请参考它们的文档获取更多示例。


这是一个很棒的软件包。我希望它能继续得到维护。 - K997

3
我会始终建议使用 ip2long,但有时需要检查网络等。我曾经构建过一个IPv4网络类,在HighOnPHP上可以找到。
与IP地址相关的好处是它的灵活性,特别是在使用位运算符时。AND、OR和BitShifting将像魔法一样起作用。

1

虽然这是一篇旧帖子,但我在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,如果没有匹配则返回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;
}

0
顺便一提,如果你需要同时检查多个范围,你可以在代码中添加几行来传递范围数组。第二个参数可以是一个数组或字符串:
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..
      // .........
}

0

这是我对这个主题的方法。

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接