import java.net.Inet4Address;
import java.net.UnknownHostException;
public final class SubNet
implements Comparable<SubNet>
{
private final byte[] address, mask;
private final int hashCode;
private String out;
private SubNet(Inet4Address net, int bits)
{
if(bits < 0 || bits > 32) {
throw new IllegalArgumentException("invalid mask");
}
mask = new byte[4];
int m = ((int) Math.pow(2, (32 - bits)) -1) ^ 0xFFFFFFFF;
for(int n = 3; n >= 0; n--) {
mask[n] = (byte) m;
m >>= 8;
}
address = net.getAddress();
for(int n = 0; n < 4; n++) {
address[n] &= mask[n];
}
String o = "" + (address[0] & 0xFF);
for(int n = 1; n < 4; n++) {
o += "." + (address[n] & 0xFF);
}
o += "|" + (mask[0] & 0xFF);
for(int n = 1; n < 4; n++) {
o += "." + (mask[n] & 0xFF);
}
out = o;
hashCode = out.hashCode();
}
@Override
public int hashCode()
{
return hashCode;
}
@Override
public boolean equals(Object obj)
{
if(this == obj) {
return true;
}
if(obj instanceof SubNet) {
SubNet o = (SubNet) obj;
return out.equals(o.out);
}
return false;
}
public boolean isInSubnet(CharSequence host)
throws UnknownHostException
{
return isInSubnet((Inet4Address) Inet4Address.getByName(host.toString()));
}
public boolean isInSubnet(Inet4Address adr)
{
byte[] tmp = adr.getAddress();
for(int n = 0; n < 4; n++) {
if((mask[n] & tmp[n]) != address[n]) {
return false;
}
}
return true;
}
@Override
public int compareTo(SubNet o)
{
return out.compareTo(o.out);
}
@Override
public String toString()
{
return out;
}
public static SubNet create(String net)
{
net = net.replace("/", "|");
String[] tmp = net.split("\\|");
return create(tmp[0], tmp[1]);
}
public static SubNet create(String address, String mask)
{
int bits = 0, m = 0;
boolean zero = false;
String[] tmp = mask.split("\\.");
if(tmp.length == 1) {
bits = Integer.parseInt(tmp[0]);
} else {
try {
Inet4Address adr = (Inet4Address) Inet4Address.getByName(mask);
for(int n = 0; n < 4; n++) {
m <<= 8;
m |= adr.getAddress()[n] & 0xFF;
}
for(int n = 0; n < 32; n++) {
if(zero) {
if((m & (1 << n)) == 0) {
throw new IllegalArgumentException("invalid mask");
}
} else {
zero = (m & (1 << n)) != 0;
bits = n;
}
}
bits = 32 - bits;
} catch(UnknownHostException e) {
return null;
}
}
return create(address, bits);
}
public static SubNet create(String address, int bits)
{
try {
Inet4Address adr = (Inet4Address) Inet4Address.getByName(address);
return create(adr, bits);
} catch(UnknownHostException e) {
return null;
}
}
public static SubNet create(Inet4Address address, int bits)
{
return new SubNet(address, bits);
}
public static void main(String[] args)
{
SubNet sn = SubNet.create("192.168.2.0/255.255.255.0");
String tst = "192.168.2.168";
boolean rng = false;
try {
rng = sn.isInSubnet(tst);
} catch(UnknownHostException e) {
e.printStackTrace();
System.exit(20);
}
System.out.println(tst + " is in");
System.out.println(sn);
System.out.println(rng);
}
}