cipv6

how to compare ipv6 address in c without using memcmp


I have two ipv6 address stored in structure struct in6_addr. I would like to find which one is smaller without using memcmp. Is there a better way to compare ipv6 addresses?

struct in6_addr {
       unsigned char   s6_addr[16];   /* IPv6 address */
};

Solution

  • In a general point of view: write what you want to do, don't use features or tricks to achieve what you want! Here, if you want compare ip v6, first, define how to compare it, and implement as you have defined.

    So don't use memcmp when you want to compare logical data. Use it only when you want to compare directly raw memory.

    For example, if you decide that you have to compare each element of ipv6 and first different elements says relation between two ipv6, write it:

    // Not checked code, just an example
    // Return 0 if ipA == ipB, -1 if ipA < ipB and 1 if ipA > ipB
    int compare_ipv6(struct in6_addr *ipA, struct in6_addr *ipB)
    {
        int i = 0;
        for(i = 0; i < 16; ++i) // Don't use magic number, here just for example
        {
            if (ipA->s6_addr[i] < ipB->s6_addr[i])
                return -1;
            else if (ipA->s6_addr[i] > ipB->s6_addr[i])
                return 1;
        }
        return 0;
    }