Posts Tagged sorting IP addresses
Sorting IP addresses in Java
Recently I had to sort a list of IP addresses. Sounds simple, but it is a little bit tricky in detail. The problem is, you can’t even sort it by string. Let’s have a look at a little example. You will get something like that:
127.0.0.100
127.0.0.2
That’s completely unusable for bigger lists of IPs!
To get the correct ordering you have to sort by bytes. Remember: all IP consists of an array of bytes. My solution is to write a Comparator for the InetAddress object, which compares each byte. A little tricky thing was to compare the bytes, because a byte is a signed value.
/** * LGPL */ public class InetAddressComparator implements Comparator<InetAddress> { @Override public int compare(InetAddress adr1, InetAddress adr2) { byte[] ba1 = adr1.getAddress(); byte[] ba2 = adr2.getAddress(); // general ordering: ipv4 before ipv6 if(ba1.length < ba2.length) return -1; if(ba1.length > ba2.length) return 1; // we have 2 ips of the same type, so we have to compare each byte for(int i = 0; i < ba1.length; i++) { int b1 = unsignedByteToInt(ba1[i]); int b2 = unsignedByteToInt(ba2[i]); if(b1 == b2) continue; if(b1 < b2) return -1; else return 1; } return 0; } private int unsignedByteToInt(byte b) { return (int) b & 0xFF; } }