// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;

public class IPMatch {
    private static int bytes2int(byte[] b) throws IOException {
        DataInputStream dis = new DataInputStream(new ByteArrayInputStream(b));
        return dis.readInt();
    }
    private static boolean check(int addr, int bits) throws IOException {
        int mask = -1 << (32 - bits);
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface nic : Collections.list(nics)) {
            Enumeration<InetAddress> nicaddrs = nic.getInetAddresses();
            for (InetAddress nicaddr : Collections.list(nicaddrs)) {
                int a = bytes2int(nicaddr.getAddress());
                if((a & mask) == (addr & mask)) {
                    return true;
                }
            }
        }
        return false;
    }
    public static boolean check(String val) throws IOException {
        String[] valparts = val.split("/");
        String[] addrparts = valparts[0].split("\\.");
        byte[] bytaddr = new byte[4];
        for(int i = 0; i < 4; i++) {
            bytaddr[i] = (byte)Short.parseShort(addrparts[i]);
        }
        int addr = bytes2int(bytaddr);
        int bits = Integer.parseInt(valparts[1]);
        return check(addr, bits);
    }
    public static void main(String[] args) throws Exception {
        System.out.println(check("172.16.0.0/24"));
        System.out.println(check("10.10.0.0/24"));
        System.out.println(check("192.168.0.0/24"));
    }
}
