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 */ }; 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; } int but bool. bool compare_ipv6(struct in6_addr *ipA, struct in6_addr *ipB, int len) { for(int i = 0; i < len; ++i) if (ipA->s6_addr[i] != ipB->s6_addr[i]) return false; return true; }result variable and (result==0) condition, using return. Moreover, you code is not doing a right comparison now: you should immediately return on < or >Use the IN6_ADDR_EQUAL function from ws2ipdef.h in Windows.
struct in6_addr?memcmpon 2s6_addrmembers? Seems like the most simple way to do the compare.s6_addrmember directlymemcmp(&a.s6_addr, &b.s6_addr, 16), you don't need to worry about struct padding.==operator is neither defined forstructnor array types.