Java judges whether two IP segments overlap

1. Background introduction

In some scenarios, it is necessary to determine whether the IP segments overlap. For example, to configure filtering rules for some devices to avoid repeated configuration of IP segments, it is necessary to check whether the IP segments overlap.

There are several scenarios where IP segments overlap:

1) IP segment 1 contains IP segment 2;
2) IP segment 2 contains IP segment 1;
3) The start IP of IP segment 1 is the same as the end IP of IP segment 2, or the end IP of IP segment 1 is the same as that of IP segment 2 The starting IP is the same;
4) IP segment 1 and IP segment 2 simply intersect.


Two, Java code implementation

code show as below:

/**
 * @author Miracle Luna
 * @date 2021/1/26
 */
public class IpUtil {
    
    

    /**
     * 判断两个IP段是否相交
     * @param ipRange1 IP段1
     * @param ipRange2 IP段2
     * @return 是否相交
     */
    public static boolean ipRange1IntersectIpRange2(String ipRange1, String ipRange2) {
    
    
        String beginIp1 = ipRange1.split("-")[0];
        String endIp1 = ipRange1.split("-")[1];

        String beginIp2 = ipRange2.split("-")[0];
        String endIp2 = ipRange2.split("-")[1];

        return getIp2Long(endIp1) >= getIp2Long(beginIp2) && getIp2Long(endIp2) >= getIp2Long(beginIp1);
    }

    /**
     * 将IP转换为Long类型
     * @param ip 待转换的IP
     * @return 转换为Long后的值
     */
    public static long getIp2Long(String ip) {
    
    
        // 去除空格
        ip = ip.trim();
        long ip2Long = 0L;

        String[] ipSplits = ip.split("\\.");
        for (String ipSplit : ipSplits) {
    
    
            ip2Long = ip2Long << 8 | Integer.parseInt(ipSplit);
        }

        return ip2Long;
    }

    public static void main(String[] args) {
    
    
        String ipRange1 = "192.168.166.10-192.168.166.216";
        String ipRange2 = "192.168.166.100-192.168.166.218";

        System.out.println("==> ipRange1IntersectIpRange2: " + ipRange1IntersectIpRange2(ipRange1, ipRange2));
    }
}

The result of the operation is as follows:

==> ipRange1IntersectIpRange2: true

Guess you like

Origin blog.csdn.net/aikudexiaohai/article/details/131656422