5

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 */ }; 
8
  • What is the type definition of struct in6_addr? Commented Jun 13, 2016 at 10:09
  • 1
    And why you cannot use memcmp on 2 s6_addr members? Seems like the most simple way to do the compare. Commented Jun 13, 2016 at 10:17
  • 1
    i can use memcmp. But what if compiler adds alignment buffer space which might be different in two structures. ? Commented Jun 13, 2016 at 10:25
  • 3
    If you take the address of s6_addr member directly memcmp(&a.s6_addr, &b.s6_addr, 16), you don't need to worry about struct padding. Commented Jun 13, 2016 at 10:32
  • 2
    @V.Kravchenko, in C the == operator is neither defined for struct nor array types. Commented Jun 13, 2016 at 10:52

2 Answers 2

4

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; } 
Sign up to request clarification or add additional context in comments.

3 Comments

1) Concise 2) -> for pointers. 3) if true or false is a result, return not 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; }
About the third point: Sorry, agree with you! And about the first point: you could get rid of result variable and (result==0) condition, using return. Moreover, you code is not doing a right comparison now: you should immediately return on < or >
Yes, now it compares properly!
0

Use the IN6_ADDR_EQUAL function from ws2ipdef.h in Windows.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.