简体   繁体   English

IP 地址重叠/在 CIDR 范围内

[英]IP Address overlapping/in range of CIDR

I have an IP address in unsigned long format, coding in C++ I have a CIDR notation IP address range such as "10.2.3.98/24"我有一个无符号长格式的 IP 地址,用 C++ 编码我有一个 CIDR 表示法 IP 地址范围,例如“10.2.3.98/24”

How do i check if my IP address overlaps with the mentioned range?如何检查我的 IP 地址是否与上述范围重叠?

To be as simple as possible, the part after the slash are the bits to keep, basically. 为了尽可能简单,斜线之后的部分都保留,基本上位。 So for example /24 means the most significant 3 bytes (24 bits) are preserved. 因此,例如,/ 24表示保留了最高3个字节(24位)。 Hence you can see if an address fits by masking it and checking for equality. 因此,可以通过掩盖地址并检查是否相等来查看地址是否适合。 The adress AND mask itself would be the min; 地址和面具本身将是最小的; If you are looking for max you can OR with the inverse of the mask. 如果您正在寻找最大值,则可以与掩码的倒数进行或运算。

This should work if you already know ip addresses as unsigned long and numbers: 如果您已经知道IP地址为无符号长和数字,这应该可以工作:

bool cidr_overlap(uint32_t ip1, int n1,
                  uint32_t ip2, int n2)
{
    return (ip1 <= (ip2 | ((1ul << (32-n2))-1)))
        || (ip2 <= (ip1 | ((1ul << (32-n1))-1)));
}

Let's Assume Your IP addresses and Masks as Follows and IP addresses are in integer form. 让我们假设您的IP地址和掩码如下,并且IP地址为整数形式。

Example 3232235896/30 ==> (actual IP 192.168.1.120/30) 示例3232235896/30 ==>(实际IP 192.168.1.120/30)

Lets say You need to find out overlap of (ip_one , mask_one) and (ip_two , mask_two) 假设您需要找出(ip_one,mask_one)和(ip_two,mask_two)的重叠

uint32_t mask_one_max = ((1ul << (32 - mask_one)) - 1);
uint32_t mask_one_min = ~mask_one_max;

uint32_t mask_two_max = ((1ul << (32 - mask_two)) - 1);
uint32_t mask_two_min = ~mask_two_max;

return (((ip_one & mask_one_min) <= (ip_two | mask_two_max)) && ((ip_two & mask_two_min) <= (ip_one | mask_one_max)));

This will return true if overlapping occurs. 如果发生重叠,则将返回true。

The Solution is Proposed based on the Generic way of finding two integer ranges overlap. 根据找到两个整数范围重叠的通用方法,提出了解决方案。 As you can see in the solution I first convert the CIDR ranges to range of Integers and use them to find the overlap. 正如您在解决方案中看到的那样,我首先将CIDR范围转换为Integers范围,然后使用它们查找重叠。

This function checks if two networks overlap.此函数检查两个网络是否重叠。

#include <arpa/inet.h>
#include <netinet/in.h>

static inline bool cidr_overlap(struct in_addr ip1, int n1, 
                                struct in_addr ip2, int n2)
{
    uint32_t mask1 = ~(((uint32_t)1 << (32 - n1)) - 1);
    uint32_t mask2 = ~(((uint32_t)1 << (32 - n2)) - 1);

    return (htonl(ip1.s_addr) & mask1 & mask2) == 
           (htonl(ip2.s_addr) & mask1 & mask2);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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