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开发PDF转Doc格式小程序

《基于Python开发PDF转Doc格式小程序》这篇文章主要为大家详细介绍了如何基于Python开发PDF转Doc格式小程序,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 用python实现PDF转Doc格式小程序以下是一个使用Python实现PDF转DOC格式的GUI程序,采用T

Nginx中location实现多条件匹配的方法详解

《Nginx中location实现多条件匹配的方法详解》在Nginx中,location指令用于匹配请求的URI,虽然location本身是基于单一匹配规则的,但可以通过多种方式实现多个条件的匹配逻辑... 目录1. 概述2. 实现多条件匹配的方式2.1 使用多个 location 块2.2 使用正则表达式

Python如何实现读取csv文件时忽略文件的编码格式

《Python如何实现读取csv文件时忽略文件的编码格式》我们再日常读取csv文件的时候经常会发现csv文件的格式有多种,所以这篇文章为大家介绍了Python如何实现读取csv文件时忽略文件的编码格式... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍我们再日常读取csv文件的时候经常

mysql线上查询之前要性能调优的技巧及示例

《mysql线上查询之前要性能调优的技巧及示例》文章介绍了查询优化的几种方法,包括使用索引、避免不必要的列和行、有效的JOIN策略、子查询和派生表的优化、查询提示和优化器提示等,这些方法可以帮助提高数... 目录避免不必要的列和行使用有效的JOIN策略使用子查询和派生表时要小心使用查询提示和优化器提示其他常

golang字符串匹配算法解读

《golang字符串匹配算法解读》文章介绍了字符串匹配算法的原理,特别是Knuth-Morris-Pratt(KMP)算法,该算法通过构建模式串的前缀表来减少匹配时的不必要的字符比较,从而提高效率,在... 目录简介KMP实现代码总结简介字符串匹配算法主要用于在一个较长的文本串中查找一个较短的字符串(称为

Nginx实现动态封禁IP的步骤指南

《Nginx实现动态封禁IP的步骤指南》在日常的生产环境中,网站可能会遭遇恶意请求、DDoS攻击或其他有害的访问行为,为了应对这些情况,动态封禁IP是一项十分重要的安全策略,本篇博客将介绍如何通过NG... 目录1、简述2、实现方式3、使用 fail2ban 动态封禁3.1 安装 fail2ban3.2 配

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Java实现检查多个时间段是否有重合

《Java实现检查多个时间段是否有重合》这篇文章主要为大家详细介绍了如何使用Java实现检查多个时间段是否有重合,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录流程概述步骤详解China编程步骤1:定义时间段类步骤2:添加时间段步骤3:检查时间段是否有重合步骤4:输出结果示例代码结语作

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Ubuntu固定虚拟机ip地址的方法教程

《Ubuntu固定虚拟机ip地址的方法教程》本文详细介绍了如何在Ubuntu虚拟机中固定IP地址,包括检查和编辑`/etc/apt/sources.list`文件、更新网络配置文件以及使用Networ... 1、由于虚拟机网络是桥接,所以ip地址会不停地变化,接下来我们就讲述ip如何固定 2、如果apt安