tags:

views:

85

answers:

3

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!!

+3  A: 

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.

paxdiablo
Not sure, but I suspect the OP is trying to sort the addresses for some data structure.
David X
A: 

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

userx
I'd prefer something like d | (c << 8) | (b << 16) | (a << 24)
SDX2000
Where are getting those numbers from? They should be `256`, `65,536` and `16,777,216` (which is one reason I prefer SDX's modification).
paxdiablo
@paxdiablo You're right, that's what you get for late night answers :) I was trying to set something up for the asker that didn't use bit shifting or OR'ing, etc.
userx
This is a a useful way to convert the bytes. Not sure why it was downvoted, possibly the (initially) incorrect multipliers but, since that's no longer the case, +1.
paxdiablo
A: 

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 
Andrew Cooper