IpParserUtil { static byte[] ip2ByteArray(String ip) { boolean ipv6Expected = false; if (ip.charAt(0) == '[') { if (ip.length() > 2 && ip.charAt(ip.length() - 1) == ']') { ip = ip.substring(1, ip.length() - 1); ipv6Expected = true; } else { throw new IllegalArgumentException(ip + ": invalid IPv6 address"); } } if (Character.digit(ip.charAt(0), 16) != -1 || (ip.charAt(0) == ':')) { byte[] address = IPAddressUtil.textToNumericFormatV4(ip); if (address != null) return address; address = IPAddressUtil.textToNumericFormatV6(ip); if (address != null) return address; if (ipv6Expected) { throw new IllegalArgumentException(ip + ": invalid IPv6 address"); } else { throw new IllegalArgumentException(ip + ": invalid IP address"); } } else { throw new IllegalArgumentException(ip + ": invalid IP address"); } }    }
@Test public void test_ip2ByteArray() throws Exception { assertArrayEquals(new byte[]{10, 1, 1, 1}, IpParserUtil.ip2ByteArray("10.1.1.1")); assertArrayEquals(new byte[]{(byte) 192, (byte) 168, (byte) 0, 13}, IpParserUtil.ip2ByteArray("192.168.0.13")); assertArrayEquals(new byte[]{10, (byte) 192, (byte) 255, 0}, IpParserUtil.ip2ByteArray("10.192.255.0")); final String ip = "2404:6800:4005:80a:0:0:0:200e"; final byte[] bytes = IpParserUtil.ip2ByteArray(ip); assertArrayEquals(getInetAddressByGetAllByName(ip).getAddress(), bytes); }
@Test public void test_ip2ByteArray_ipv4_exception() throws Exception { try { IpParserUtil.ip2ByteArray("a.1.1.1"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } try { IpParserUtil.ip2ByteArray("-2.168.0.13"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } try { IpParserUtil.ip2ByteArray("1.1.1.256"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } try { IpParserUtil.ip2ByteArray("192.168.0.13.1"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } }
@Test public void test_ip2ByteArray_ipv6_exception() throws Exception { try { IpParserUtil.ip2ByteArray("2404:6800:4005:80a:0:0:0:200z"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } try { IpParserUtil.ip2ByteArray("-2404:6800:4005:80a:0:0:0:200e"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } try { IpParserUtil.ip2ByteArray("2404:6800:4005:80a:0:0:0:200:123"); fail(); } catch (IllegalArgumentException expected) { expected.printStackTrace(); } }