Sorting IP addresses

D

David Zimmerman

Mar said:
Any idea how to sort IP addresses?

If you have them in an int (4 octets do, after all, make a 32 bit word
that looks like an int), they compare easily and naturally, just sort
'em (EG using Array.sort()). They will sort from 128.0.0.0 all the way
up to 127.255.255.255 (signed vs unsigned byte)

If you have them as InetAddress's, call GetAddress() and stuff the
byte[4] into an int and proceed as above.

If you have some other idea of sort order and/or you have your IP
addresses in some other format, it may be easier to write a Comparator()
that understands your requirements and hand the whole thing off to
Collections.sort()
 
R

Roedy Green

A word to the wise: IPv6.

those are 128 bits, or 16 bytes.

You could write a comparator like this:




public final int compare ( Object a, Object b )
{

byte[] aa = (( Inet6Address) a).getAddress();
byte[] bb = (( Inet6Address) b).getAddress();

for (int i=0; i<16; i++)
{
if ( aa != bb )
{
return (aa & 0xff) - (bb & 0xff);
}
}
return 0;

} // end compare


It is time for java to acquire an octet (unsigned byte) even if the
gode generates is an automatic & 0xff. I bet 99% of the time the
signed byte gets loaded unsigned by the hardware, then signed
extended, then chopped back with &0xff.
 
M

Marco Schmidt

Mar Thomas:
Any idea how to sort IP addresses?

I convert them to long values (an int cannot hold unsigned 32 bit
values) and sort those long values. Also makes it easy to check if an
IP is from a certain range, simply convert beginning and ending
address to long and do simple >= and <= comparisons. Likewise, that
sort of "is contained?" checking can be done with a bitwise AND if the
range is given in the ADDRESS/BITS notation.

Regards,
Marco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top