From eb59d21431e595a9fff556e96742bbb080fd1a92 Mon Sep 17 00:00:00 2001 From: hjc Date: Mon, 4 Jan 2021 22:44:58 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=9D=E8=AF=95=E6=B7=BB=E5=8A=A0ipv6?= =?UTF-8?q?=E7=9B=B8=E5=85=B3=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/cn/hutool/core/net/NetUtil.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/hutool-core/src/main/java/cn/hutool/core/net/NetUtil.java b/hutool-core/src/main/java/cn/hutool/core/net/NetUtil.java index 910887cd3..0924c2da7 100644 --- a/hutool-core/src/main/java/cn/hutool/core/net/NetUtil.java +++ b/hutool-core/src/main/java/cn/hutool/core/net/NetUtil.java @@ -10,6 +10,7 @@ import cn.hutool.core.util.StrUtil; import java.io.IOException; import java.io.OutputStream; +import java.math.BigInteger; import java.net.DatagramSocket; import java.net.HttpCookie; import java.net.IDN; @@ -33,6 +34,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; +import java.util.regex.Pattern; /** * 网络相关工具 @@ -76,6 +78,53 @@ public class NetUtil { return Ipv4Util.ipv4ToLong(strIP); } + /** + * 检测给定的IP字符串符合哪个版本 + * @param ipStr 需要检测的字符串 + * @return 版本号['IPv4', 'IPv6', 'Neither'] + */ + public static String getIpVersion(String ipStr) { + Pattern patternIpv4 = Pattern.compile("^(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}$"); + Pattern patternIpv6 = Pattern.compile("^((([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}(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\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}))$"); + if (patternIpv6.matcher(ipStr).matches()) { + return "IPv6"; + } else if (patternIpv4.matcher(ipStr).matches()) { + return "IPv4"; + } else { + return "Neither"; + } + } + + /** + * 将IPv6地址字符串转为大整数 + * + * @param IPv6Str 字符串 + * @return 大整数, 如发生异常返回 null + */ + public static BigInteger ipv6ToBitInteger(String IPv6Str) { + try { + InetAddress address = InetAddress.getByName(IPv6Str); + if (address instanceof Inet6Address) { + return new BigInteger(1, address.getAddress()); + } + } catch (UnknownHostException e) {} + return null; + } + + /** + * 将大整数转换成ipv6字符串 + * + * @param bigInteger 大整数 + * @return IPv6字符串, 如发生异常返回 null + */ + public static String bigIntegerToIPv6(BigInteger bigInteger) { + try { + String ipv6 = InetAddress.getByAddress(bigInteger.toByteArray()).toString().substring(1); + return ipv6; + } catch (UnknownHostException e) {} + return null; + } + /** * 检测本地端口可用性
* 来自org.springframework.util.SocketUtils