mirror of
https://gitee.com/chinabugotech/hutool.git
synced 2025-04-19 03:01:48 +08:00
添加一个带默认值的 Ipv4Util.ipv4ToLong 方法
This commit is contained in:
parent
96c9a3529c
commit
916a56dac3
@ -4,6 +4,7 @@ import cn.hutool.core.collection.ListUtil;
|
|||||||
import cn.hutool.core.convert.Convert;
|
import cn.hutool.core.convert.Convert;
|
||||||
import cn.hutool.core.lang.Assert;
|
import cn.hutool.core.lang.Assert;
|
||||||
import cn.hutool.core.lang.PatternPool;
|
import cn.hutool.core.lang.PatternPool;
|
||||||
|
import cn.hutool.core.lang.Validator;
|
||||||
import cn.hutool.core.util.CharUtil;
|
import cn.hutool.core.util.CharUtil;
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
|
||||||
@ -168,6 +169,16 @@ public class Ipv4Util {
|
|||||||
throw new IllegalArgumentException("Invalid IPv4 address!");
|
throw new IllegalArgumentException("Invalid IPv4 address!");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ip地址(xxx.xxx.xxx.xxx)计算出long型的数据, 如果格式不正确返回 defaultValue
|
||||||
|
* @param strIP IP V4 地址
|
||||||
|
* @param defaultValue 默认值
|
||||||
|
* @return long值
|
||||||
|
*/
|
||||||
|
public static long ipv4ToLong(String strIP, long defaultValue) {
|
||||||
|
return Validator.isIpv4(strIP) ? ipv4ToLong(strIP) : defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据 ip/掩码位 计算IP段的起始IP(字符串型)
|
* 根据 ip/掩码位 计算IP段的起始IP(字符串型)
|
||||||
* 方法别名:inet_ntoa
|
* 方法别名:inet_ntoa
|
||||||
|
@ -86,4 +86,17 @@ public class Ipv4UtilTest {
|
|||||||
l = Ipv4Util.ipv4ToLong("255.255.255.255");
|
l = Ipv4Util.ipv4ToLong("255.255.255.255");
|
||||||
Assert.assertEquals(4294967295L, l);
|
Assert.assertEquals(4294967295L, l);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ipv4ToLongWithDefaultTest() {
|
||||||
|
String strIP = "不正确的 IP 地址";
|
||||||
|
long defaultValue = 0L;
|
||||||
|
long ipOfLong = Ipv4Util.ipv4ToLong(strIP, defaultValue);
|
||||||
|
Assert.assertEquals(ipOfLong, defaultValue);
|
||||||
|
|
||||||
|
String strIP2 = "255.255.255.255";
|
||||||
|
long defaultValue2 = 0L;
|
||||||
|
long ipOfLong2 = Ipv4Util.ipv4ToLong(strIP2, defaultValue2);
|
||||||
|
Assert.assertEquals(ipOfLong2, 4294967295L);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user