How would you compare two IP addresses to see which one is greater?
For example, following are two sets of IP addresses, now, how would you identify the greater IP for each set?
SET A:
10.192.3.177 and 10.192.2.204
SET B:
10.192.3.205 and 10.192.2.204开发者_开发百科
Thanks!!
If you convert them to a 32-bit integer, the greater one will be the greater integer. In other words:
10.192.3.177 -> 0x0ac003b1 (180,356,017) (bigger)
10.192.2.204 -> 0x0ac002cc (180,355,788)
10.192.3.205 -> 0x0ac003cd (180,356,045) (bigger)
10.192.2.204 -> 0x0ac002cc (180,355,788)
I'm having a hard time imagining a use case where it would matter but that's the approach I would take if I had to check in a program.
You should probably clarify what you mean by "greater".
But the numerical (uint32) value of each IP address can be calculated with:
d + 256 * c + 65536 * b + 16777216 * a
where a, b, c, and d are the base 10 values in an IPv4 formatted: a.b.c.d
If you're after a way to sort a list of IP's you can also store the IP in a string with each octet prepended by 0 to 3 digits. Then a text sort works fine.
Example:
010.192.002.204
010.192.003.177
精彩评论