Hi all,
How to compress Ipv6 addresses? Are there any existing API's in Java which offer the functionality?
For example the compressed equivalent of the Ipv6 address 3ffe:0000:0000:0000:0000:0000:0000:0001
is 3ffe::1
Regards,
Printable View
Hi all,
How to compress Ipv6 addresses? Are there any existing API's in Java which offer the functionality?
For example the compressed equivalent of the Ipv6 address 3ffe:0000:0000:0000:0000:0000:0000:0001
is 3ffe::1
Regards,
I took the liberty of studying the RFC for IPv6 and then I created this method.
Code :/** * This method takes an IPv6 address and compresses it according to the RFC (http://www.ietf.org/rfc/rfc2373.txt). * * @param uncompressed the uncompressed IPv6 address * @return a compressed IPv6 address */ public static String compressIpv6(final String uncompressed) { if (uncompressed == null) { return null; } if (uncompressed.contains("::")) { return uncompressed; } if (uncompressed.equals("0:0:0:0:0:0:0:0")) { return "::"; } int start = -1; int end = -1; for (int i = 0; i < uncompressed.length(); ++i) { final char character = uncompressed.charAt(i); if (start == -1) { if (character == '0' && i > 0 && uncompressed.charAt(i - 1) == ':') { start = i - 1; } else if (character == '0' && i == 0) { start = 0; } } else { if (character != '0' && character != ':') { if (uncompressed.charAt(i - 1) == ':') { end = i; } break; } } } if (start > -1 && end > start) { return uncompressed.substring(0, start) + "::" + uncompressed.substring(end, uncompressed.length()); } return uncompressed; }
It might be flawed but I tested it with the following addresses:
FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
3ffe:0000:0000:0000:0000:0000:0000:0001
1080:0:0:0:8:800:200C:417A
FF01:0:0:0:0:0:0:101
0:0:0:0:0:0:0:1
0:0:0:0:0:0:0:0
Feel free to use it if you dare :)
// Json
Thanks Json,
But unfortunately the code doesn't work fine for lot of cases. I have written the code. It works fine for all cases. For example
"2001:0:000:00:1:0000:1:2",
"2001:000:1:000:1:0:1:1"
it fails.
Thanks,
Could you explain, when you say fail, do you mean that you get an exception or that the output is simply not what you expect it to be?
Could you also give me a few examples of some addresses you say are not working, what they are uncompressed and what you expect to see once compressed?
// Json
I am sorry to say 'fail' , I meant that the compression is not proper for e.g.
2001:0:000:00:1:0000:1:2-Compressed form should be 2001::1:0:2
"2001:000:1:000:1:0:1:1 -Compressed form should be 2001:0:1:0:1:0:1:1
I see so all :0000: which are not affected by the :: should still be truncated down to :0: :D
Let's see if we can fix that :D
// Json