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实现IP地址和端口状态检测与监控

《使用Python实现IP地址和端口状态检测与监控》在网络运维和服务器管理中,IP地址和端口的可用性监控是保障业务连续性的基础需求,本文将带你用Python从零打造一个高可用IP监控系统,感兴趣的小伙... 目录概述:为什么需要IP监控系统使用步骤说明1. 环境准备2. 系统部署3. 核心功能配置系统效果展

Java中的StringBuilder之如何高效构建字符串

《Java中的StringBuilder之如何高效构建字符串》本文将深入浅出地介绍StringBuilder的使用方法、性能优势以及相关字符串处理技术,结合代码示例帮助读者更好地理解和应用,希望对大家... 目录关键点什么是 StringBuilder?为什么需要 StringBuilder?如何使用 St

MyBatis模糊查询报错:ParserException: not supported.pos 问题解决

《MyBatis模糊查询报错:ParserException:notsupported.pos问题解决》本文主要介绍了MyBatis模糊查询报错:ParserException:notsuppo... 目录问题描述问题根源错误SQL解析逻辑深层原因分析三种解决方案方案一:使用CONCAT函数(推荐)方案二:

MySQL 中的 JSON 查询案例详解

《MySQL中的JSON查询案例详解》:本文主要介绍MySQL的JSON查询的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 的 jsON 路径格式基本结构路径组件详解特殊语法元素实际示例简单路径复杂路径简写操作符注意MySQL 的 J

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

Python如何精准判断某个进程是否在运行

《Python如何精准判断某个进程是否在运行》这篇文章主要为大家详细介绍了Python如何精准判断某个进程是否在运行,本文为大家整理了3种方法并进行了对比,有需要的小伙伴可以跟随小编一起学习一下... 目录一、为什么需要判断进程是否存在二、方法1:用psutil库(推荐)三、方法2:用os.system调用

Nginx location匹配模式与规则详解

《Nginxlocation匹配模式与规则详解》:本文主要介绍Nginxlocation匹配模式与规则,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、环境二、匹配模式1. 精准模式2. 前缀模式(不继续匹配正则)3. 前缀模式(继续匹配正则)4. 正则模式(大

HTML5表格语法格式详解

《HTML5表格语法格式详解》在HTML语法中,表格主要通过table、tr和td3个标签构成,本文通过实例代码讲解HTML5表格语法格式,感兴趣的朋友一起看看吧... 目录一、表格1.表格语法格式2.表格属性 3.例子二、不规则表格1.跨行2.跨列3.例子一、表格在html语法中,表格主要通过< tab

MySQL索引的优化之LIKE模糊查询功能实现

《MySQL索引的优化之LIKE模糊查询功能实现》:本文主要介绍MySQL索引的优化之LIKE模糊查询功能实现,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前缀匹配优化二、后缀匹配优化三、中间匹配优化四、覆盖索引优化五、减少查询范围六、避免通配符开头七、使用外部搜索引擎八、分

Java 正则表达式URL 匹配与源码全解析

《Java正则表达式URL匹配与源码全解析》在Web应用开发中,我们经常需要对URL进行格式验证,今天我们结合Java的Pattern和Matcher类,深入理解正则表达式在实际应用中... 目录1.正则表达式分解:2. 添加域名匹配 (2)3. 添加路径和查询参数匹配 (3) 4. 最终优化版本5.设计思