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;
    }
}
相关推荐
liulilittle13 小时前
俄罗斯访问欧洲国际线路优化
开发语言·网络·信息与通信·ip·通信·俄罗斯·莫斯科
我药打十个3 天前
搭建稳定的ip代理池方法
爬虫·计算机网络·ip·ip代理池
阿巴~阿巴~4 天前
“可达”方能“可靠”:深入解析网络层在TCP通信中的基石作用
运维·服务器·网络·网络协议·tcp/ip·ip·tcp
GateWorld4 天前
FPGA DSP模块使用中不易察觉的坑
fpga开发·ip·实战经验·fpga dsp使用
阿巴~阿巴~5 天前
深入解析IP分片:从原理到现代实践的全面指南
运维·服务器·网络·网络协议·tcp/ip·ip
阿巴~阿巴~5 天前
路由的本质:从逐跳转发到全球互联的决策机制解析
网络·网络协议·tcp/ip·智能路由器·ip·tcp·路由
阿巴~阿巴~5 天前
私网与公网的协同之道:NAT、IP架构与互联网连接全景解析
网络·网络协议·tcp/ip·架构·ip·tcp·公网私网ip
源远流长jerry5 天前
curl、ping、iptables、iperf、tcpdump解析
网络·网络协议·测试工具·ip·tcpdump
科技块儿7 天前
跨境电商用户IP真实性评估:高精度查询与离线库的融合策略
数据库·网络协议·tcp/ip·ip
baboon_chen12 天前
iproute2——ip
ip·linux网络命令