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

相关文章

从入门到精通MySQL联合查询

《从入门到精通MySQL联合查询》:本文主要介绍从入门到精通MySQL联合查询,本文通过实例代码给大家介绍的非常详细,需要的朋友可以参考下... 目录摘要1. 多表联合查询时mysql内部原理2. 内连接3. 外连接4. 自连接5. 子查询6. 合并查询7. 插入查询结果摘要前面我们学习了数据库设计时要满

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

mysql表操作与查询功能详解

《mysql表操作与查询功能详解》本文系统讲解MySQL表操作与查询,涵盖创建、修改、复制表语法,基本查询结构及WHERE、GROUPBY等子句,本文结合实例代码给大家介绍的非常详细,感兴趣的朋友跟随... 目录01.表的操作1.1表操作概览1.2创建表1.3修改表1.4复制表02.基本查询操作2.1 SE

Mysql常见的SQL语句格式及实用技巧

《Mysql常见的SQL语句格式及实用技巧》本文系统梳理MySQL常见SQL语句格式,涵盖数据库与表的创建、删除、修改、查询操作,以及记录增删改查和多表关联等高级查询,同时提供索引优化、事务处理、临时... 目录一、常用语法汇总二、示例1.数据库操作2.表操作3.记录操作 4.高级查询三、实用技巧一、常用语

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

XML重复查询一条Sql语句的解决方法

《XML重复查询一条Sql语句的解决方法》文章分析了XML重复查询与日志失效问题,指出因DTO缺少@Data注解导致日志无法格式化、空指针风险及参数穿透,进而引发性能灾难,解决方案为在Controll... 目录一、核心问题:从SQL重复执行到日志失效二、根因剖析:DTO断裂引发的级联故障三、解决方案:修复

利用Python脚本实现批量将图片转换为WebP格式

《利用Python脚本实现批量将图片转换为WebP格式》Python语言的简洁语法和库支持使其成为图像处理的理想选择,本文将介绍如何利用Python实现批量将图片转换为WebP格式的脚本,WebP作为... 目录简介1. python在图像处理中的应用2. WebP格式的原理和优势2.1 WebP格式与传统

mysql查询使用_rowid虚拟列的示例

《mysql查询使用_rowid虚拟列的示例》MySQL中,_rowid是InnoDB虚拟列,用于无主键表的行ID查询,若存在主键或唯一列,则指向其,否则使用隐藏ID(不稳定),推荐使用ROW_NUM... 目录1. 基本查询(适用于没有主键的表)2. 检查表是否支持 _rowid3. 注意事项4. 最佳实

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

python判断文件是否存在常用的几种方式

《python判断文件是否存在常用的几种方式》在Python中我们在读写文件之前,首先要做的事情就是判断文件是否存在,否则很容易发生错误的情况,:本文主要介绍python判断文件是否存在常用的几种... 目录1. 使用 os.path.exists()2. 使用 os.path.isfile()3. 使用