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;
    }
}
相关推荐
怣疯knight15 小时前
几个好用的ip纯净度检测网站
网络·ip
明月心9526 天前
IP 中 0/24 和 0/16 的区别
linux·服务器·网络·ip
Han.miracle13 天前
网络层-IP 协议全景解析:从地址分配到内网穿透,解锁互联网通信底层密码
服务器·网络·网络协议·ip
泰克生物15 天前
纳米二抗:破解 IP 实验痛点,多场景赋能免疫检测的高效工具
ip·亲和力·wb·ip-wb·纳米二抗·特异性
cccyi715 天前
网络层与 IP 协议详解
tcp/ip·ip·网络层
老蒋新思维1 个月前
借陈修超之智,搭建 AI 与 IP 的创新增长桥梁|创客匠人
网络·人工智能·网络协议·tcp/ip·ip·知识付费·创客匠人
戴草帽的大z1 个月前
在 rk3588上通过网络命名空间实现 eth0/eth1 网卡隔离与程序独立部署
linux·网络·rk3588·ip·iproute·网卡隔离·ip netns
教练、我想打篮球1 个月前
29 ip查询工具 并发送邮件通知目标用户
tcp/ip·ip·query
2401_841495641 个月前
【计算机网络】计算机网络体系结构与参考模型
网络·计算机网络·ip·tcp·osi·分层结构·协议数据单元
观山岳五楼2 个月前
unbuntu系统配置IPV6的三种模式
linux·服务器·ip·1024程序员节