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

2023-12-16 02:04

本文主要是介绍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

这篇关于IP段(CIDR格式)构建匹配库,传入IP查询是否命中的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/498706

相关文章

Python中判断对象是否为空的方法

《Python中判断对象是否为空的方法》在Python开发中,判断对象是否为“空”是高频操作,但看似简单的需求却暗藏玄机,从None到空容器,从零值到自定义对象的“假值”状态,不同场景下的“空”需要精... 目录一、python中的“空”值体系二、精准判定方法对比三、常见误区解析四、进阶处理技巧五、性能优化

使用Python构建一个Hexo博客发布工具

《使用Python构建一个Hexo博客发布工具》虽然Hexo的命令行工具非常强大,但对于日常的博客撰写和发布过程,我总觉得缺少一个直观的图形界面来简化操作,下面我们就来看看如何使用Python构建一个... 目录引言Hexo博客系统简介设计需求技术选择代码实现主框架界面设计核心功能实现1. 发布文章2. 加

SQL表间关联查询实例详解

《SQL表间关联查询实例详解》本文主要讲解SQL语句中常用的表间关联查询方式,包括:左连接(leftjoin)、右连接(rightjoin)、全连接(fulljoin)、内连接(innerjoin)、... 目录简介样例准备左外连接右外连接全外连接内连接交叉连接自然连接简介本文主要讲解SQL语句中常用的表

Python中使用正则表达式精准匹配IP地址的案例

《Python中使用正则表达式精准匹配IP地址的案例》Python的正则表达式(re模块)是完成这个任务的利器,但你知道怎么写才能准确匹配各种合法的IP地址吗,今天我们就来详细探讨这个问题,感兴趣的朋... 目录为什么需要IP正则表达式?IP地址的基本结构基础正则表达式写法精确匹配0-255的数字验证IP地

MySQL高级查询之JOIN、子查询、窗口函数实际案例

《MySQL高级查询之JOIN、子查询、窗口函数实际案例》:本文主要介绍MySQL高级查询之JOIN、子查询、窗口函数实际案例的相关资料,JOIN用于多表关联查询,子查询用于数据筛选和过滤,窗口函... 目录前言1. JOIN(连接查询)1.1 内连接(INNER JOIN)1.2 左连接(LEFT JOI

MySQL 中查询 VARCHAR 类型 JSON 数据的问题记录

《MySQL中查询VARCHAR类型JSON数据的问题记录》在数据库设计中,有时我们会将JSON数据存储在VARCHAR或TEXT类型字段中,本文将详细介绍如何在MySQL中有效查询存储为V... 目录一、问题背景二、mysql jsON 函数2.1 常用 JSON 函数三、查询示例3.1 基本查询3.2

MySQL中的交叉连接、自然连接和内连接查询详解

《MySQL中的交叉连接、自然连接和内连接查询详解》:本文主要介绍MySQL中的交叉连接、自然连接和内连接查询,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、引入二、交php叉连接(cross join)三、自然连接(naturalandroid join)四

mysql的基础语句和外键查询及其语句详解(推荐)

《mysql的基础语句和外键查询及其语句详解(推荐)》:本文主要介绍mysql的基础语句和外键查询及其语句详解(推荐),本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋... 目录一、mysql 基础语句1. 数据库操作 创建数据库2. 表操作 创建表3. CRUD 操作二、外键

浅谈配置MMCV环境,解决报错,版本不匹配问题

《浅谈配置MMCV环境,解决报错,版本不匹配问题》:本文主要介绍浅谈配置MMCV环境,解决报错,版本不匹配问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录配置MMCV环境,解决报错,版本不匹配错误示例正确示例总结配置MMCV环境,解决报错,版本不匹配在col

详解nginx 中location和 proxy_pass的匹配规则

《详解nginx中location和proxy_pass的匹配规则》location是Nginx中用来匹配客户端请求URI的指令,决定如何处理特定路径的请求,它定义了请求的路由规则,后续的配置(如... 目录location 的作用语法示例:location /www.chinasem.cntestproxy