验证IP地址(带掩码) [英] Validate an IP Address (with Mask)
问题描述
我有IP地址和掩码,例如 10.1.1.1/32
。我想检查 10.1.1.1
是否在该范围内。是否有一个库或实用程序可以做到这一点,或者我需要自己写一些东西? 解决方案
首先,您需要将您的IP地址转换为平面 int
s,这将更易于使用:
String s =10.1.1.99;
Inet4Address a =(Inet4Address)InetAddress.getByName(s);
byte [] b = a.getAddress();
int i =((b [0]& 0xFF)<24} |
((b [1]& 0xFF)<< 16)|
((b [2]& 0xFF)<< 8)|
((b [3]& 0xFF)<< 0);
将IP地址设为普通 int
你可以做一些算术来执行检查:
pre $ int $ subnet = 0x0A010100; // 10.1.1.0/24
int bits = 24;
int ip = 0x0A010199; // 10.1.1.99
//创建位掩码来清除不相关的位。对于10.1.1.0/24,这是
// 0xFFFFFF00 - 前24位是1,最后8位是0。
//
// -1 == 0xFFFFFFFF
// 32 - 位== 8
// -1 << 8 == 0xFFFFFF00
mask = -1<< (32位)
if((subnet& mask)==(ip& mask)){
// IP地址在子网中。
}
I have ip addresses and a mask such as 10.1.1.1/32
. I would like to check if 10.1.1.1
is inside that range. Is there a library or utility that would do this or do I need to write something myself?
First you'll want to convert your IP addresses into flat int
s, which will be easier to work with:
String s = "10.1.1.99";
Inet4Address a = (Inet4Address) InetAddress.getByName(s);
byte[] b = a.getAddress();
int i = ((b[0] & 0xFF) << 24) |
((b[1] & 0xFF) << 16) |
((b[2] & 0xFF) << 8) |
((b[3] & 0xFF) << 0);
Once you have your IP addresses as plain int
s you can do some bit arithmetic to perform the check:
int subnet = 0x0A010100; // 10.1.1.0/24
int bits = 24;
int ip = 0x0A010199; // 10.1.1.99
// Create bitmask to clear out irrelevant bits. For 10.1.1.0/24 this is
// 0xFFFFFF00 -- the first 24 bits are 1's, the last 8 are 0's.
//
// -1 == 0xFFFFFFFF
// 32 - bits == 8
// -1 << 8 == 0xFFFFFF00
mask = -1 << (32 - bits)
if ((subnet & mask) == (ip & mask)) {
// IP address is in the subnet.
}
这篇关于验证IP地址(带掩码)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!