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;
    }
}
相关推荐
2401_873479402 天前
如何识别代理IP和伪装流量?用IP情报工具三步穿透住宅代理伪装
网络·数据库·网络协议·tcp/ip·ip
IpdataCloud3 天前
AI生成的Avalon恶意框架怎么防?用IP离线库识别模块化C2通信
运维·人工智能·网络协议·tcp/ip·ip
treesforest3 天前
高精度IP定位怎么选?从企业需求出发的选型指南
网络·数据库·tcp/ip·web安全·ip·高精度ip查询
ShineWinsu5 天前
对于Linux:网络基础的解析
linux·网络·面试·udp·笔试·ip·tcp
重庆优沃科技6 天前
选IP广播时该参考哪些通用标准来判断其专业性?
ip
liulilittle7 天前
KCC 边界缺陷深度分析:六问题根源与解决方案
网络·网络协议·tcp/ip·计算机网络·信息与通信·ip·通信
儒雅的烤地瓜8 天前
计算机网络 | 路由器局域网(内网)IP和外网(公网)IP的区别与联系
网关·tcp/ip·智能路由器·ip·外网·内网·nat技术
未来侦察班1 个月前
网络协议 网络层,万物归于IP
网络·网络协议·协议·ip·网络层·tcpip
袁小皮皮不皮1 个月前
1.HCIP BFD 学习笔记(优化版)
服务器·网络·笔记·网络协议·学习·智能路由器·ip
2401_873479401 个月前
如何用IP离线库阻断挖矿和僵尸网络?DNS层防护实战指南
网络·网络协议·tcp/ip·ip