验证 IP 地址(使用掩码)

2022-09-05 00:17:23

我有IP地址和掩码,例如.我想检查是否在该范围内。有没有一个库或实用程序可以做到这一点,或者我需要自己写一些东西?10.1.1.1/3210.1.1.1


答案 1

首先,您需要将IP地址转换为平面s,这将更容易使用:int

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);

一旦你的IP地址是普通的,你可以做一些算术来执行检查:int

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.
}

答案 2
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;
        }
}

推荐