是否存在用于在Java中存储IP地址的特定数据类型?我有一个特定的功能要求:
我知道,java.net.inetaddress但我相信它不会给我这个功能.有任何想法吗?
Pau*_*aul 13
IP(IPv4)是32位(与Java中的int相同).由于您希望使用无符号整数进行比较(如果您需要支持IP高于128.0.0.0),则需要使用long.
10.10.10.1 is: (10 << 24) + (10 << 16) + (10 << 8) + 1 = 168430081
10.10.11.255 is: (10 << 24) + (10 << 16) + (11 << 8) + 255 = 168430591
10.10.10.192 is: (10 << 24) + (10 << 16) + (10 << 8) + 192 = 168430272
Run Code Online (Sandbox Code Playgroud)
因为168430081 <= 168430272 && 168430272 <= 168430591,(换句话说168430272介于168430081和168430272之间),您的IP在此范围内.
nd.*_*nd. 13
我会使用java.net.InetAddress或其中一个子类并编写自定义比较器和范围类:
InetAddress的一个缺点是getByName导致DNS访问.如果你想避免DNS的惩罚,你可能想看看Guava的com.google.common.net.InetAddresses助手类.
public enum InetAddressComparator implements Comparator<InetAddress> {
INSTANCE;
public int compare(InetAddress first, InetAddress second) {
byte[] firstBytes = first.getAddress();
byte[] secondBytes = second.getAddress();
if (firstBytes.length != secondBytes.length) {
throw new IllegalArgumentException("Cannot compare IPv4 and IPv6 addresses");
}
// getAddress returns bytes in network byte order:
// the least significant byte is at the last index
for (int i = firstBytes.length - 1; i >= 0; i--) {
// translate the byte to an int with only the last 8 bits set,
// effectively treating it as unsigned
int a = firstBytes[i] & 0xff;
int b = secondBytes[i] & 0xff;
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
}
return 0;
}
}
public class Range<T> {
private T lower;
private T upper;
private Comparator<T> comparator;
public Range(T lower, T upper, Comparator<T> comparator) {
if (comparator.compare(lower, upper) <= 0) {
this.lower = lower;
this.upper = upper;
} else {
this.lower = upper;
this.upper = lower;
}
this.comparator = comparator;
}
public boolean contains(T element) {
return comparator.compare(lower, element) <= 0 &&
comparator.compare(upper, element) >= 0;
}
}
public class Main {
public static void main(String[] args) throws Exception {
InetAddress start = InetAddress.getByName("10.10.10.1");
InetAddress end = InetAddress.getByName("10.10.11.255");
InetAddress test = InetAddress.getByName("10.10.10.192");
assert InetAddressComparator.INSTANCE.compare(start, test) == -1;
assert InetAddressComparator.INSTANCE.compare(end, test) == 1;
assert InetAddressComparator.INSTANCE.compare(test, test) == 0;
assert new Range<InetAddress>(start, end, InetAddressComparator.INSTANCE)
.contains(test);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20481 次 |
| 最近记录: |