Search code examples
ccidr

IP cidr match function


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

ip = 192.168.0.1 mask = 192.168.0.1/24.

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

How can i compare ip and cidr range ?


Solution

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