IP段(CIDR格式)构建匹配库,传入IP查询是否命中

代码中有一些没用的自行去掉,我使用的CIDR格式,也可以通过IP的范围改造一下代码使用。

导入依赖

        <dependency><groupId>com.github.seancfoley</groupId><artifactId>ipaddress</artifactId><version>5.3.3</version></dependency>

IP匹配库工具类

package com.chun.utils;import inet.ipaddr.AddressStringException;
import inet.ipaddr.IPAddress;
import inet.ipaddr.IPAddressSeqRange;
import inet.ipaddr.IPAddressString;
import org.apache.commons.net.util.SubnetUtils;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;/*** @author chun* @date 2023/12/14 16:24*/
public class IPMatcher {private static List<IPAddressSeqRange> ipRanges = new ArrayList<>();public static void readFile(File file) {try (BufferedReader reader = new BufferedReader(new FileReader(file))) {String line;while ((line = reader.readLine()) != null) {setIpRanges(line);}} catch (IOException e) {e.printStackTrace();}}public static boolean isIpRanges(String address) throws AddressStringException {for (IPAddressSeqRange ipRange : ipRanges) {boolean contains = ipRange.contains(new IPAddressString(address).toAddress());if (contains) {return true;}}return false;}public static void setIpRanges(String cidrAddress) {String startAddress = "";String endAddress = "";try {String[] split = cidrAddress.split("\\/");SubnetUtils utils = new SubnetUtils(cidrAddress);SubnetUtils.SubnetInfo subnetInfo = utils.getInfo();if (split[1].equals("32")) {startAddress = split[0];endAddress = split[0];} else {startAddress = subnetInfo.getLowAddress();endAddress = subnetInfo.getHighAddress();}System.out.println("IP CIDR=" + cidrAddress + ",IP范围:[" + startAddress + ", " + endAddress + "]");} catch (IllegalArgumentException e) {try {InetAddress networkAddress = InetAddress.getByName(cidrAddress.split("/")[0]);int subnetPrefixLength = Integer.parseInt(cidrAddress.split("/")[1]);BigInteger start = getStartAddress(networkAddress, subnetPrefixLength);BigInteger end = getEndAddress(start, subnetPrefixLength);startAddress = getAddressFromBigInteger(start);endAddress = getAddressFromBigInteger(end);System.out.println("IP CIDR=" + cidrAddress + ",IP范围:[" + startAddress + ", " + endAddress + "]");} catch (UnknownHostException ex) {ex.printStackTrace();}}IPAddress startIPAddress = new IPAddressString(startAddress).getAddress();IPAddress endIPAddress = new IPAddressString(endAddress).getAddress();ipRanges.add(startIPAddress.toSequentialRange(endIPAddress));}private static BigInteger getStartAddress(InetAddress networkAddress, int subnetPrefixLength) {ByteBuffer buffer = ByteBuffer.wrap(networkAddress.getAddress());BigInteger start = new BigInteger(1, buffer.array());return start.shiftRight(128 - subnetPrefixLength).shiftLeft(128 - subnetPrefixLength);}private static BigInteger getEndAddress(BigInteger start, int subnetPrefixLength) {BigInteger hostCount = BigInteger.ONE.shiftLeft(128 - subnetPrefixLength);return start.add(hostCount).subtract(BigInteger.ONE);}private static String getAddressFromBigInteger(BigInteger address) {byte[] bytes = address.toByteArray();InetAddress inetAddress;try {if (bytes.length == 16) {inetAddress = InetAddress.getByAddress(bytes);} else {byte[] paddedBytes = new byte[16];System.arraycopy(bytes, 0, paddedBytes, 16 - bytes.length, bytes.length);inetAddress = InetAddress.getByAddress(paddedBytes);}return inetAddress.getHostAddress();} catch (UnknownHostException e) {e.printStackTrace();}return null;}
}

构建匹配库和读取配置文件

package com.chun.conf;import com.chun.utils.IPMatcher;
import lombok.extern.slf4j.Slf4j;import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;/*** @author chun* @date 2023/12/14 15:58*/
@Slf4j
public class ReadConf {public static String url;public static String userName;public static String passWord;public static String userIpDir;public static String userIpFileMatch;public static void initPropertoesConf() throws IOException {Properties properties = new Properties();FileInputStream file = new FileInputStream(System.getProperty("user.dir") + "/test_pgsql/etc/conf.properties");properties.load(file);url = properties.getProperty("pgsql.url");userName = properties.getProperty("pgsql.userName");passWord = properties.getProperty("pgsql.passWord");userIpDir = properties.getProperty("user.ip.filepath");userIpFileMatch = properties.getProperty("user.ip.fileMatch");}public static void initUserIpConf() throws Exception {File[] files = getFiles(userIpDir, userIpFileMatch);if (files == null || files.length == 0) {log.error("The conf.properties user IP file path is incorrect! IP file number is 0");return;}for (File file : files) {IPMatcher.readFile(file);}}private static File[] getFiles(String dir, String fileNameMatch) {File fileDir = new File(dir);File[] files;if (fileDir.isDirectory()) {FileFilter fileFilter = new FileFilter() {@Overridepublic boolean accept(File file) {//判断文件名是否符合通配符规则return file.getName().matches(fileNameMatch);}};files = fileDir.listFiles(fileFilter);} else {files = new File[1];files[0] = fileDir;}return files;}
}

conf.properties

pgsql.url=jdbc:postgresql://localhost:5432/School
pgsql.userName=postgres
pgsql.passWord=123456
user.ip.filepath=E:\\ProjectWorker\\TestJob\\test_pgsql\\etc\\
user.ip.fileMatch=ip.*

测试

传入文件列表:文件内容如下:

192.168.12.5/32
192.177.12.1/24
192.169.12.1/16
2001:0db8:85a3::/64
2001:0db8:85a4::/128
@Slf4j
public class Main {public static void main(String[] args) {ReadConf.initPropertoesConf();log.info("Start read conf.properties success!");ReadConf.initUserIpConf();log.info("Start read ip conf success!");System.out.println(IPMatcher.isIpRanges("192.168.1.1"));System.out.println(IPMatcher.isIpRanges("192.168.12.5"));System.out.println(IPMatcher.isIpRanges("192.177.12.1"));System.out.println(IPMatcher.isIpRanges("192.177.255.1"));System.out.println(IPMatcher.isIpRanges("192.169.255.254"));System.out.println(IPMatcher.isIpRanges("192.170.255.254"));System.out.println(IPMatcher.isIpRanges("2001:0db8:85a3::1234"));System.out.println(IPMatcher.isIpRanges("2001:0db8:85a4::ffff"));System.out.println(IPMatcher.isIpRanges("2001:0db8:85a4::"));}
}

结果

[INFO ] 2023-12-15 10:01:46.879 - Start read conf.properties success!
IP CIDR=192.168.12.5/32IP范围:[192.168.12.5, 192.168.12.5]
IP CIDR=192.177.12.1/24IP范围:[192.177.12.1, 192.177.12.254]
IP CIDR=192.169.12.1/16IP范围:[192.169.0.1, 192.169.255.254]
IP CIDR=2001:0db8:85a3::/64IP范围:[2001:db8:85a3:0:0:0:0:0, 2001:db8:85a3:0:ffff:ffff:ffff:ffff]
IP CIDR=2001:0db8:85a4::/128IP范围:[2001:db8:85a4:0:0:0:0:0, 2001:db8:85a4:0:0:0:0:0]
[INFO ] 2023-12-15 10:01:47.145 - Start read ip conf success!
false
true
true
false
true
false
true
false
true

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/225497.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RocketMQ系统性学习-RocketMQ领域模型及Linux下单机安装

MQ 之间的对比 三种常用的 MQ 对比&#xff0c;ActiveMQ、Kafka、RocketMQ 性能方面&#xff1a; 三种 MQ 吞吐量级别为&#xff1a;万&#xff0c;百万&#xff0c;十万消息发送时延&#xff1a;毫秒&#xff0c;毫秒&#xff0c;微秒可用性&#xff1a;主从&#xff0c;分…

可删除背包(计数类): P4141

https://www.luogu.com.cn/problem/P4141 看完第一眼想到打分治&#xff0c;然后记得以前打abc时好像见到过一种可撤销背包。 使用条件&#xff1a; 计数类&#xff0c;非最优性问题物品之间顺序无影响 因此我们直接撤销是对的

PyQt6 QFrame分割线控件

锋哥原创的PyQt6视频教程&#xff1a; 2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 PyQt6 Python桌面开发 视频教程(无废话版) 玩命更新中~共计46条视频&#xff0c;包括&#xff1a;2024版 PyQt6 Python桌面开发 视频教程(无废话版…

消除非受检警告

在Java中&#xff0c;有一些情况下编译器会生成非受检警告&#xff08;Unchecked Warnings&#xff09;。这些警告通常与泛型、类型转换或原始类型相关。消除这些警告可以提高代码的可读性和安全性。以下是一些常见的非受检警告以及如何消除它们的例子&#xff1a; 1. 泛型类型…

STM32-UART-DMA HAL库缓冲收发

文章目录 1、说明1.1、注意事项&#xff1a;1.2、接收部分1.3、发送部分 2、代码2.1、初始化2.2、缓冲接收2.3、缓冲发送2.4、格式化打印 1、说明 1.1、注意事项&#xff1a; HAL库的DMA底层基本都会默认开启中断使能&#xff0c;如果在STM32CubeMx禁用了中断相关的功能&…

【WinForm.NET开发】使用 FlowLayoutPanel 在 Windows 窗体上排列控件

本文内容 创建项目水平和垂直排列控件更改流方向插入流中断使用停靠和锚定来定位控件使用填充和边距排列控件通过在工具箱中双击来插入控件通过绘制控件轮廓来插入控件使用插入条来插入控件将现有控件重新分配给不同的父控件后续步骤 某些应用程序要求窗体布局在窗体调整大小…

人工智能与量子计算:开启未知领域的智慧之旅

导言 人工智能与量子计算的结合是科技领域的一场创新盛宴&#xff0c;引领我们进入了探索未知领域的新时代。本文将深入研究人工智能与量子计算的交汇点&#xff0c;探讨其原理、应用以及对计算领域的深远影响。 量子计算的崛起为人工智能领域注入了新的活力&#xff0c;开启了…

利用canvas封装录像时间轴拖动(uniapp),封装上传uniapp插件市场

gitee项目地址,项目是一个空项目,其中包含了封装的插件,自己阅读,由于利用了canvas所以在使用中暂不支持.nvue,待优化; 项目也是借鉴了github上的一个项目,timeline-canvas,​​​​​​​ ​​​​​​​

GPT-4V被超越?SEED-Bench多模态大模型测评基准更新

&#x1f4d6; 技术报告 SEED-Bench-1&#xff1a;https://arxiv.org/abs/2307.16125 SEED-Bench-2&#xff1a;https://arxiv.org/abs/2311.17092 &#x1f917; 测评数据 SEED-Bench-1&#xff1a;https://huggingface.co/datasets/AILab-CVC/SEED-Bench SEED-Bench-2&…

纽扣电池是什么

纽扣电池 电工电气百科 文章目录 纽扣电池前言一、纽扣电池是什么二、纽扣电池的类别三、纽扣电池的作用原理总结前言 纽扣电池具有易于更换的特点,这使得它们成为许多便携设备的理想电源选择。但是,由于它们较小且外壳易于打开,所以家中有婴幼儿的家庭应特别注意将其放置在…

抓包工具:Sunny网络中间件

Sunny网络中间件 和 Fiddler 类似。 是可跨平台的网络分析组件 可用于HTTP/HTTPS/WS/WSS/TCP/UDP网络分析 为二次开发量身制作 支持 获取/修改 HTTP/HTTPS/WS/WSS/TCP/TLS-TCP/UDP 发送及返回数据 支持 对 HTTP/HTTPS/WS/WSS 指定连接使用指定代理 支持 对 HTTP/HTTPS/WS/WSS/T…

Mybatis-Plus利用Sql注入器批量插入更新

Mybatis-Plus是在Mybatis持久层框架上封装的一层非常好用的工具&#xff0c;最近因为想要在Mapper里加入自己自定义的通用方法&#xff0c;所以用到了Mybatis-Plus的Sql注入器。Sql注入器的作用是可以实现自定义的sql脚本并注入到MappedStatement里&#xff0c;从而达到动态拼装…

[css] flex wrap 九宫格布局

<div class"box"><ul class"box-inner"><li>九宫格1</li><li>九宫格2</li><li>九宫格3</li><li>九宫格4</li><li>九宫格5</li><li>九宫格6</li><li>九宫格7&l…

【算法提升—力扣每日一刷】五日总结【12/06--12/10】

文章目录 2023/12/06力扣每日一刷&#xff1a;[206. 反转链表](https://leetcode.cn/problems/reverse-linked-list/) 2023/12/07力扣每日一刷&#xff1a;[203. 移除链表元素](https://leetcode.cn/problems/remove-linked-list-elements/)力扣今日两刷&#xff1a;[19. 删除链…

iOS_给View的部分区域截图 snapshot for view

文章目录 1.将整个view截图返回image&#xff1a;2.截取view的部分区域&#xff0c;返回image&#xff1a;3.旧方法&#xff1a;4.Tips参考&#xff1a; 1.将整个view截图返回image&#xff1a; 这些 api 已被废弃&#xff0c;所以需要判断 iOS 版本 写两套代码&#xff1a; R…

NVMe over Fabrics with SPDK with iRDMA总结 - 1

1.0 Introduction简介 NVM Express* (NVMe*) drives are high-speed, low-latency, solid-state drives (SSDs), that connect over the server Peripheral Component Interconnect Express* (PCIe*) bus. NVM Express* (NVMe*) 硬盘是高速、低延迟的固态硬盘 (SSD),通过服…

轻松制作健身预约小程序

如果你想制作一个健身预约小程序&#xff0c;实现高效预约与健身管理&#xff0c;可以按照以下步骤进行操作。 第一步&#xff1a;注册登录乔拓云平台&#xff0c;进入后台 第二步&#xff1a;点击【轻应用小程序】&#xff0c;进入设计小程序页面。 第三步&#xff1a;在设计小…

Python基础(八、random模块探秘)

大家好&#xff0c;今天我要和你们聊一聊一个非常有趣的Python模块——random。它就像是一个疯狂的抽签者&#xff0c;总是在背后悄悄地为我们制造出各种各样的随机事件。让我们一起来揭开random的神秘面纱&#xff0c;看看它到底能带给我们哪些惊喜&#xff01; 文章目录 1. …

uniGUI学习之Cookie

UniApplication.Cookies.SetCookie( const ACookieName: string, const AValue: string, AExpires: TDateTime 0, ASecure: Boolean False, AHTTPOnly: Boolean False, const APath: string / )

多汗症的预防措施有哪些?

多汗症的预防措施主要包括以下几个方面&#xff0c;通过这些措施&#xff0c;可以有效地减少多汗症的发生&#xff0c;提高生活质量。 一、保持身体清洁 保持身体清洁是预防多汗症的重要措施之一。每天洗澡&#xff0c;特别是在运动或出汗后&#xff0c;及时更换衣物&#xf…