понедельник, 13 февраля 2012 г.

IPUtils.java

Надеюсь этот код, в каком либо видео попадет в apache commons


import java.net.Inet4Address;
import java.net.InetAddress;


public class IPUtils {


    static int convert(String ip) {
        try {
            Inet4Address a = (Inet4Address) InetAddress.getByName(ip);
            byte[] b = a.getAddress();
            int i = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | (b[3] << 0);
            return i;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static boolean checkIPMask(String ip, String mask) {
        int ipp = convert(ip);
        String m[] = mask.split("/");
        int subnet = convert(m[0]);
        int bits = Integer.decode(m[1]);


        // 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.
        //
        // --> 32 - bits == 8
        // --> 1 << 8 == 0x00000100
        // --> (1 << 8) - 1 == 0x000000FF
        // --> ~((1 << 8) - 1) == 0xFFFFFF00
        int maskk = ~((1 << (32 - bits)) - 1);


        return ((subnet & maskk) == (ipp & maskk));
    }


    public static boolean checkIPMasks(String ip, String[] masks) {
        for (String mask : masks) {
            if (checkIPMask(ip, mask))
                return true;
        }


        return false;
    }


}

0 коммент.:

Отправить комментарий