Java quickly judges whether an IP is within a given network segment

To Javadetermine whether one IP地址is within a given network segment in , you can use 子网掩码will IP地址and 子网掩码carry 与操作to extract the network address and compare it to the address of a given subnet.

Method 1: With the help of InetAddress provided by Java

The examples below are ChatGPTprovided .

insert image description here

The code is as follows (the calculation of the subnet mask can be obtained by intercepting the string with the help of the algorithm at the bottom):

public static boolean isIpAddressInSubnet(String ipAddress, String subnetAddress, String subnetMask) throws UnknownHostException {
    
    
    InetAddress inetAddress = InetAddress.getByName(ipAddress);
    InetAddress subnet = InetAddress.getByName(subnetAddress);
    InetAddress mask = InetAddress.getByName(subnetMask);

    byte[] inetAddressBytes = inetAddress.getAddress();
    byte[] subnetBytes = subnet.getAddress();
    byte[] maskBytes = mask.getAddress();

    for (int i = 0; i < inetAddressBytes.length; i++) {
    
    
        int addressByte = inetAddressBytes[i] & 0xFF;
        int subnetByte = subnetBytes[i] & 0xFF;
        int maskByte = maskBytes[i] & 0xFF;

        if ((addressByte & maskByte) != (subnetByte & maskByte)) {
    
    
            return false;
        }
    }

    return true;
}

This method accepts three arguments: what to check IP地址, 子网地址and 子网掩码. It uses InetAddressclasses to convert these strings into Java objects, and then converts them into byte arrays. It then iterates over each byte and compares the value of each byte with the corresponding subnet byte and mask byte to extract the network address. Return if the network address does not match the subnet address, falseotherwise true.

For example, suppose we want to check if IP address " 192.168.1.100" is in subnet " 192.168.1.0/24":

boolean result = isIpAddressInSubnet("192.168.1.100", "192.168.1.0", "255.255.255.0");
if (result) {
    
    
    System.out.println("IP address is in subnet");
} else {
    
    
    System.out.println("IP address is not in subnet");
}

Method 2: implement an algorithm (binary calculation)

The code comes from Google, but it is enough to understand the principle, and there is no need to delve into it. In any case, it will definitely need IP 地址and 子网掩码to form a subnet range; and then judge IPwhether in this network segment.

/**
 * 判断是否在该网段中
 *
 * @param subnetRange 子网范围 x.x.x.x/xx 形式
 */
public static boolean isIpAddressInSubnet(String ipAddress, String subnetRange) {
    
    
    String[] networkips = ipAddress.split("\\.");
    int ipAddr = (Integer.parseInt(networkips[0]) << 24)
            | (Integer.parseInt(networkips[1]) << 16)
            | (Integer.parseInt(networkips[2]) << 8)
            | Integer.parseInt(networkips[3]);
            
    // 拿到主机数       
    int type = Integer.parseInt(subnetRange.replaceAll(".*/", ""));
    int ipCount = 0xFFFFFFFF << (32 - type);
    
    String maskIp = subnetRange.replaceAll("/.*", "");
    String[] maskIps = maskIp.split("\\.");
    
    int cidrIpAddr = (Integer.parseInt(maskIps[0]) << 24)
            | (Integer.parseInt(maskIps[1]) << 16)
            | (Integer.parseInt(maskIps[2]) << 8)
            | Integer.parseInt(maskIps[3]);
            
    return (ipAddr & ipCount) == (cidrIpAddr & ipCount);
}

For example, suppose we want to check if IP address " 192.168.1.100" is in subnet " 192.168.1.0/24":

boolean result = isIpAddressInSubnet("192.168.1.100", "192.168.1.0/24");
if (result) {
    
    
    System.out.println("IP address is in subnet");
} else {
    
    
    System.out.println("IP address is not in subnet");
}

other

number to subnet mask

public static String subnetMaskFromPrefixLength(int prefixLength) {
    
    
    if (prefixLength < 0 || prefixLength > 32) {
    
    
        throw new IllegalArgumentException("Invalid prefix length");
    }

    int mask = 0xffffffff << (32 - prefixLength);
    return String.format("%d.%d.%d.%d",
        (mask & 0xff000000) >>> 24,
        (mask & 0x00ff0000) >>> 16,
        (mask & 0x0000ff00) >>> 8,
        (mask & 0x000000ff));
}

Example:

String subnetMask = subnetMaskFromPrefixLength(24);
System.out.println(subnetMask); // 输出:255.255.255.0

Personal blog: Roc's Blog

Guess you like

Origin blog.csdn.net/peng2hui1314/article/details/129027169