This commit is contained in:
孙继峰 2021-04-19 10:56:43 +08:00 committed by GitHub
parent 36a4a84474
commit 3ce1cbab8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 4 additions and 11 deletions

View File

@ -73,11 +73,7 @@ public class IPUtil {
* @return boolean
*/
public static boolean isIPv4(String addr) {
try {
return InetAddress.getByName(addr).getAddress().length == IPV4_ADDRESS_LENGTH;
} catch (UnknownHostException e) {
return false;
}
return ipv4Pattern.matcher(addr).matches();
}
/**
@ -101,12 +97,7 @@ public class IPUtil {
* @return boolean
*/
public static boolean isIP(String addr) {
try {
InetAddress.getByName(addr);
return true;
} catch (UnknownHostException e) {
return false;
}
return isIPv4(addr) || isIPv6(addr);
}
/**

View File

@ -33,6 +33,7 @@ public class IPUtilTest {
Assert.assertFalse(IPUtil.isIPv4("[::1]"));
Assert.assertFalse(IPUtil.isIPv4("asdfasf"));
Assert.assertFalse(IPUtil.isIPv4("ffgertert"));
Assert.assertFalse(IPUtil.isIPv4("127.100.19"));
}
@Test
@ -47,6 +48,7 @@ public class IPUtilTest {
Assert.assertTrue(IPUtil.isIP("[::1]"));
Assert.assertTrue(IPUtil.isIP("127.0.0.1"));
Assert.assertFalse(IPUtil.isIP("er34234"));
Assert.assertFalse(IPUtil.isIP("127.100.19"));
}
@Test