IP CIDR匹配功能 [英] IP cidr match function

查看:728
本文介绍了IP CIDR匹配功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找出来的,是IP属于IP掩码。
例如:

I need to find out, is ip belong to ip mask. For example:

IP = 192.168.0.1
面膜= 192.168.0.1/24。

ip = 192.168.0.1 mask = 192.168.0.1/24.

我发现,转换为IP屏蔽功能:

I found function that convert ip to mask:

inet_cidrtoaddr(int cidr, struct in_addr *addr)
{
        int ocets;

        if (cidr < 0 || cidr > 32) {
                errno = EINVAL;
                return -1;
        }
        ocets = (cidr + 7) / 8;

        addr->s_addr = 0;
        if (ocets > 0) {
                memset(&addr->s_addr, 255, (size_t)ocets - 1);
                memset((unsigned char *)&addr->s_addr + (ocets - 1),
                       (256 - (1 << (32 - cidr) % 8)), 1);
        }

        return 0;
}

我如何比较IP和CIDR范围是多少?

How can i compare ip and cidr range ?

推荐答案

如果你的IP地址,网络地址,网络掩码,那么你可以使用这样的功能:

If you have the IP address, the network address, and the netmask, then you can use a function like this:

bool
is_in_net (
        const struct in_addr*   addr,     /* host byte order */
        const struct in_addr*   netaddr,
        const struct in_addr*   netmask
        )
{
   if ((addr->s_addr & netmask->s_addr) == (netaddr->s_addr & netmask->s_addr))
      return true;
   return false;
}

这篇关于IP CIDR匹配功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆