There are two IP address validation utils:
sun.net.util.IPAddressUtil
org.apache.commons.validator.routines.InetAddressValidator
I made some tests for both.
`IPAddressUtil` tests:
// NOTE:
// Got the following warning in Travis:
// warning: IPAddressUtil is internal proprietary API and may be removed in a future release
public class IPAddressUtilTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testIsIPv4LiteralAddress() {
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3.0"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3.4"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3.255"));
assertFalse(IPAddressUtil.isIPv4LiteralAddress("1.2.3.256"));
assertFalse(IPAddressUtil.isIPv4LiteralAddress("1.2.3."));
// NOTE: They look weird but valid.
// See http://stackoverflow.com/questions/7550806/check-valid-ipv4-address-in-java
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2.3"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1.2"));
assertTrue(IPAddressUtil.isIPv4LiteralAddress("1"));
assertFalse(IPAddressUtil.isIPv4LiteralAddress(""));
assertFalse(IPAddressUtil.isIPv4LiteralAddress("::1"));
thrown.expect(NullPointerException.class);
IPAddressUtil.isIPv4LiteralAddress(null);
}
@Test
public void testIsIPv6LiteralAddress() {
assertTrue(IPAddressUtil.isIPv6LiteralAddress("::1"));
assertFalse(IPAddressUtil.isIPv6LiteralAddress("1.2.3.4"));
}
}
`InetAddressValidator` tests:
public class InetAddressValidatorTests {
InetAddressValidator validator = InetAddressValidator.getInstance();
@Test
public void testIsValidInet4Address() {
assertTrue(validator.isValidInet4Address("1.2.3.0"));
assertTrue(validator.isValidInet4Address("1.2.3.4"));
assertTrue(validator.isValidInet4Address("1.2.3.255"));
assertFalse(validator.isValidInet4Address("1.2.3.256"));
assertFalse(validator.isValidInet4Address("1.2.3."));
assertFalse(validator.isValidInet4Address("1.2.3"));
assertFalse(validator.isValidInet4Address("1.2"));
assertFalse(validator.isValidInet4Address("1"));
assertFalse(validator.isValidInet4Address(""));
assertFalse(validator.isValidInet4Address("::1"));
assertFalse(validator.isValidInet4Address(null));
}
@Test
public void testIsValidInet6Address() {
assertTrue(validator.isValidInet6Address("::1"));
assertFalse(validator.isValidInet6Address("1.2.3.4"));
}
}
As you can see the above tests,
they work differently.
Don't use `IPAddressUtil`.
I got the following warning from Travis builds when I used it:
warning: IPAddressUtil is internal proprietary API and may be removed in a future release
No comments:
Post a Comment