Search code examples
c++ip-addressequalsipv6mask

Comparing two IPv6 addresses and their masks (windows)


I have to compare two IPv6 addresses and their masks to see if they are the same. They are both in strings, such as "xxxx:xxxx:xxxx:xxxx/xx". I would just use memcmp to compare them bit by bit, however this may return false when true, due to the fact that xxxx:xxxx:0000:xxxx/xx and xxxx:xxxxx::xxxxx/xx are technically the same address.

I would prefer not to create substrings of the addresses and masks, but I will if there's a function that compares two IPv6 addresses. Any suggestions? :)


Solution

  • You should convert both addressed to binary form using inet_pton and then compare the binary forms (which are just 16 bytes of data you can compare with memcmp).

    If you need to compare masked addresses then you will have to do a little more work. inet_pton will not parse prefix lengths ("/something") for you so you will have to:

    1. Find the slash
    2. Pass the part before the slash to inet_pton
    3. Parse the integer after the slash with plain ol' atoi
    4. Manually zero out 128 minus that number of bits at the end of the binary form of the address

    ...on each address before comparing them.