Code example for TreeMap

Methods: containsKey, containsValue, get, lastKey, put

0
     */ 
    public static boolean netMatch(String addr1, String addr2) {
        TreeMap<String, Integer> subnet1 = extractIPandMask(addr1);
        TreeMap<String, Integer> subnet2 = extractIPandMask(addr2);
 
        if (subnet1.containsValue(0) && subnet2.containsValue(0)) {
            if (subnet1.containsKey(subnet2.lastKey())) {
                return true; 
            } 
        } 
 
        Inet4Address a1 = null;
        Inet4Address a2 = null;
        try { 
            a1 = (Inet4Address) InetAddress.getByName(subnet1.lastKey());
            a2 = (Inet4Address) InetAddress.getByName(subnet2.lastKey());
        } catch (UnknownHostException e) {
        } 
 
        byte[] b = a1.getAddress();
        int ipInt = ((b[0] & 0xFF) << 24)
                | ((b[1] & 0xFF) << 16)
                | ((b[2] & 0xFF) << 8)
                | ((b[3] & 0xFF) << 0);
 
        byte[] b1 = a2.getAddress();
        int ipInt1 = ((b1[0] & 0xFF) << 24)
                | ((b1[1] & 0xFF) << 16)
                | ((b1[2] & 0xFF) << 8)
                | ((b1[3] & 0xFF) << 0);
 
        int mask = ~((1 << (32 - subnet1.get(subnet1.lastKey()))) - 1);
 
        if ((ipInt & mask) == (ipInt1 & mask)) {
            return true; 
        } else { 
            return false; 
        } 
    } 
 
    /** 
     * Extract the IP and the mask given an IP address 
     * 
     * @param addr in String format (e.g. 192.168.1.0/24 or 192.168.1.50) 
     * @return 
     */ 
    public static TreeMap<String, Integer> extractIPandMask(String addr) {
        TreeMap<String, Integer> subnet = new TreeMap<String, Integer>();
        String[] parts = addr.split("/");
        String ip = parts[0];
        int mask;
        if (parts.length < 2) {
            mask = 0;
        } else { 
            mask = Integer.parseInt(parts[1]);
        } 
        subnet.put(ip, mask);
        return subnet;
    } 
 
    /** 
     * The string is a subnet address, contains the mask