Search code examples
c++cnetwork-programmingipv6

is there any code for bitwise and ipv6 address and network mask (prefix)?


I want to ask about calculation of ipv6 network and host side.

For example, I have the IPv6 address 2001:470:1f15:1bcd:34::41 and prefix 96.

Do you know a easy way to do bitwise and between IPv6 address and prefix?

According to IPv4:

192.168.1.2  255.255.255.0  network : 192.168.1.0

So simple.

I want to do the same thing to IPv6 address. But IPv6 address is 16 bytes, so you can't use unsigned int for that.

Is there any API to do this? Or should I use arrays?


Solution

  • See the functions in6_addr_mask and in6_addr_start from in6calc.c.

    Example usage:

    struct in6_addr addr, mask, start;
    char addr_buffer[INET6_ADDRSTRLEN] = "2001:470:1f15:1bcd:34::41";
    uint8_t bits = 96; 
    
    inet_pton(AF_INET6, addr_buffer, &addr);
    
    in6_addr_mask(&mask, bits); // Mask
    in6_addr_start(&start, &addr, &mask); // Bitwise &
    
    inet_ntop(AF_INET6, &start, addr_buffer, INET6_ADDRSTRLEN);
    printf("Network:    %s\n", addr_buffer);
    

    Yields:

    Network:    2001:470:1f15:1bcd:34::