Validate an IP Address (with Mask)
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 = 0x0A010163; // 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.
}
public static boolean netMatch(String addr, String addr1){ //addr is subnet address and addr1 is ip address. Function will return true, if addr1 is within addr(subnet)
String[] parts = addr.split("/");
String ip = parts[0];
int prefix;
if (parts.length < 2) {
prefix = 0;
} else {
prefix = Integer.parseInt(parts[1]);
}
Inet4Address a =null;
Inet4Address a1 =null;
try {
a = (Inet4Address) InetAddress.getByName(ip);
a1 = (Inet4Address) InetAddress.getByName(addr1);
} catch (UnknownHostException e){}
byte[] b = a.getAddress();
int ipInt = ((b[0] & 0xFF) << 24) |
((b[1] & 0xFF) << 16) |
((b[2] & 0xFF) << 8) |
((b[3] & 0xFF) << 0);
byte[] b1 = a1.getAddress();
int ipInt1 = ((b1[0] & 0xFF) << 24) |
((b1[1] & 0xFF) << 16) |
((b1[2] & 0xFF) << 8) |
((b1[3] & 0xFF) << 0);
int mask = ~((1 << (32 - prefix)) - 1);
if ((ipInt & mask) == (ipInt1 & mask)) {
return true;
}
else {
return false;
}
}