IP地址工具,判断IP是否在指定范围内(支持ipv6)

常用方法,判断一个ip是否在指定的ip范围内,范围可能包括起始ip范围或者掩码形式,无其它依赖,

java 复制代码
package com.yk.ip;

import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class IpUtil {

    /**
     * 判断目标ip是否在ip范围内(起始ip范围),支持ipv6
     * @param ipAddress 目标ip
     * @param startIp 开始ip
     * @param endIp 结束ip
     * @return boolean
     * @throws UnknownHostException 异常
     */
    public static boolean isInRange(String ipAddress,String startIp,String endIp) throws UnknownHostException {
        InetAddress address = InetAddress.getByName(ipAddress);
        InetAddress startAddress = InetAddress.getByName(startIp);
        InetAddress endAddress = InetAddress.getByName(endIp);
        BigInteger start = new BigInteger(1, startAddress.getAddress());
        BigInteger end = new BigInteger(1, endAddress.getAddress());
        BigInteger target = new BigInteger(1, address.getAddress());
        int st = start.compareTo(target);
        int te = target.compareTo(end);
        return (st <= 0) && (te <= 0);
    }

    /**
     * 判断目标ip是否在ip范围内(掩码),支持ipv6
     * @param ipAddress 目标ip
     * @param ipWithMask 带掩码ip
     * @return boolean
     * @throws UnknownHostException 异常
     */
    public static boolean isInRange(String ipAddress,String ipWithMask) throws UnknownHostException {
        if (ipWithMask.contains("/")) {
            String addressPart = ipWithMask.substring(0, ipWithMask.indexOf("/"));
            String networkPart = ipWithMask.substring(ipWithMask.indexOf("/") + 1);
            ByteBuffer maskBuffer;
            int targetSize;
            InetAddress inetAddress = InetAddress.getByName(addressPart);
            if (inetAddress.getAddress().length == 4) {
                maskBuffer = ByteBuffer
                                .allocate(4)
                                .putInt(-1);
                targetSize = 4;
            } else {
                maskBuffer = ByteBuffer.allocate(16)
                        .putLong(-1L)
                        .putLong(-1L);
                targetSize = 16;
            }
            BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(Integer.parseInt(networkPart));

            ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
            BigInteger ipVal = new BigInteger(1, buffer.array());

            BigInteger startIp = ipVal.and(mask);
            BigInteger endIp = startIp.add(mask.not());

            byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize);
            byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize);

            InetAddress startAddress = InetAddress.getByAddress(startIpArr);
            InetAddress endAddress = InetAddress.getByAddress(endIpArr);
            return isInRange(ipAddress, startAddress.getHostAddress(), endAddress.getHostAddress());
        } else {
            throw new IllegalArgumentException("not an valid CIDR format!");
        }
    }

    private static byte[] toBytes(byte[] array, int targetSize) {
        int counter = 0;
        List<Byte> newArr = new ArrayList<Byte>();
        while (counter < targetSize && (array.length - 1 - counter >= 0)) {
            newArr.add(0, array[array.length - 1 - counter]);
            counter++;
        }

        int size = newArr.size();
        for (int i = 0; i < (targetSize - size); i++) {

            newArr.add(0, (byte) 0);
        }

        byte[] ret = new byte[newArr.size()];
        for (int i = 0; i < newArr.size(); i++) {
            ret[i] = newArr.get(i);
        }
        return ret;
    }
}
相关推荐
xhbh6661 天前
路由端口转发常见应用场景有哪些?有什么?
服务器·ip·端口转发·ip地址·流量转发·建站
xhbh6666 天前
netsh端口转发:隐藏网站IP的流量转发方案
ip·流量端口转发·netsh 端口转发
treesforest7 天前
IP查询接口调用完全指南:从入门到企业级实战
大数据·网络·安全·网络安全·ip
Jiangxl~8 天前
IP数据云如何为不同行业提供精准IP查询与风险防控解决方案?
网络·网络协议·tcp/ip·算法·ai·ip·安全架构
承渊政道9 天前
用群晖部署OmniBox+pansou:把分散的影视资源全聚合到一个界面里
服务器·windows·网络协议·https·ip·视频·持续部署
聊点儿技术12 天前
LLM数据采集如何突破AI反爬?——用IP数据接口实现进阶
人工智能·数据分析·产品运营·ip·电商·ip地址查询·ip数据接口
treesforest12 天前
Ipdatacloud IP 地址查询方案适合哪些场景?
大数据·网络·数据库·网络协议·tcp/ip·ip
聊点儿技术12 天前
物联网设备IP归属地查询实操指南
物联网·tcp/ip·ip·ip归属地查询·ip地址查询·查ip归属地
承渊政道13 天前
群晖配Plex搭建私人影音中心,用起来到底怎么样?
服务器·windows·网络协议·https·ip·视频·持续部署
聊点儿技术14 天前
物联网设备出海如何用IP归属地查询解决“定位漂移”?
物联网·ip·物联网安全·ip地址查询·ip离线库·查ip归属地·物联网出海