mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-05-09 23:51:34 +08:00
Ipv4Util 新增方法:检测指定 IP 地址是否匹配通配符 pattern
This commit is contained in:
parent
15d53726f7
commit
bfcb2b7d51
@ -366,6 +366,33 @@ public class Ipv4Util {
|
|||||||
return isInnerIp;
|
return isInnerIp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测指定 IP 地址是否匹配通配符 wildcard
|
||||||
|
*
|
||||||
|
* @param pattern 通配符,如 192.168.*.1
|
||||||
|
* @param ipAddress 待检测的 IP 地址
|
||||||
|
* @return 是否匹配
|
||||||
|
*/
|
||||||
|
public static boolean matches(String pattern, String ipAddress) {
|
||||||
|
if (!Validator.isMatchRegex(PatternPool.IPV4, ipAddress)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String[] patternSegments = pattern.split("\\.");
|
||||||
|
String[] ipSegments = ipAddress.split("\\.");
|
||||||
|
|
||||||
|
if (patternSegments.length != ipSegments.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < patternSegments.length; i++) {
|
||||||
|
if (!"*".equals(patternSegments[i]) && !patternSegments[i].equals(ipSegments[i])) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
//-------------------------------------------------------------------------------- Private method start
|
//-------------------------------------------------------------------------------- Private method start
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -107,6 +107,15 @@ public class Ipv4UtilTest {
|
|||||||
Assert.assertFalse("掩码位非法检验", maskBitValid);
|
Assert.assertFalse("掩码位非法检验", maskBitValid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void matchesTest() {
|
||||||
|
boolean matches1 = Ipv4Util.matches("127.*.*.1", "127.0.0.1");
|
||||||
|
Assert.assertTrue("IP地址通配符匹配1", matches1);
|
||||||
|
|
||||||
|
boolean matches2 = Ipv4Util.matches("192.168.*.1", "127.0.0.1");
|
||||||
|
Assert.assertFalse("IP地址通配符匹配2", matches2);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void ipv4ToLongTest(){
|
public void ipv4ToLongTest(){
|
||||||
long l = Ipv4Util.ipv4ToLong("127.0.0.1");
|
long l = Ipv4Util.ipv4ToLong("127.0.0.1");
|
||||||
|
Loading…
x
Reference in New Issue
Block a user