Karsten
Karsten

Reputation: 1907

Comparing IP v6 addresses

has anybody some good ideas to compare two ipv6 addresses. It look like the shortage rules are making it complicated.

for instance the full address 1234:0db8:0000:0000:0000:ff00:ff00:0011

  1. leading zero can be removed => 1234:0db8::::ff00:ff00:11
  2. one group of empty fields can be removed 1234:0db8::ff00:ff00:00111
  3. the last 32 bit can be an old fashioned ipv4 address 1234:0db8::::ff00:172.0.0.15

Upvotes: 0

Views: 97

Answers (2)

MattH
MattH

Reputation: 38247

You can use the standard library function socket.inet_pton to convert the addresses into a byte string for comparison:

>>> socket.inet_pton(socket.AF_INET6,'1234:0db8::ff00:ff00:0011')
'\x124\r\xb8\x00\x00\x00\x00\x00\x00\xff\x00\xff\x00\x00\x11'
>>> socket.inet_pton(socket.AF_INET6,'1234:0db8:0000:0000:0000:ff00:ff00:0011')
'\x124\r\xb8\x00\x00\x00\x00\x00\x00\xff\x00\xff\x00\x00\x11'

This will reduce the risk of you creating your own IPv6 bug.


Example above is in python, but the inet_pton function is available on different platforms and languages:

Upvotes: 2

skylla
skylla

Reputation: 464

You could just split it by colons and then compare each value. If you encounter an empty field -> insert '0000' for it. If you encounter a field with less than 4 digits -> fill it up with zeroes

Additionally you could give each of the fields a weight to emphasize the values of the fields.

Upvotes: 0

Related Questions