验证InetSocketAddresses的正则表达式(ipv4/v6 +端口地址) [英] Regular expression to validate InetSocketAddresses (ipv4/v6 + port addresses)
问题描述
I am looking for tested regular expressions for both ipv4 and ipv6 InetSocketAddress (i.e., ip address + port number). I am not interested in validating hostnames.
它可以是两个正则表达式(一个用于ipv4,一个用于ipv6)或一个组合的正则表达式.
It can be two regex (one for ipv4, one for ipv6) or one combined regex.
有人可以分享吗?
编辑
有关ip4格式的信息,请参见此处,有关ipv6格式的信息,请参见此处一个>.然后,在端口号上添加:".
For ip4 format information see here, for ipv6 format information see here. Then, port number is added with ':'.
编辑2 要创建字符串表示形式,我将像这样进行操作:
EDIT 2 To create a string representation, I will proceed like this:
byte[] tmp = { 10, 1, 0, 0 };
InetSocketAddress isa = new InetSocketAddress(
InetAddress.getByAddress(tmp), 443);
返回:
/10.1.0.0:443
推荐答案
尝试在InetSocketAddress
的.toString()
上使用正则表达式来执行此操作可能不是一个好主意. (请参阅上述问题的评论)
Trying to use a regex on the .toString()
of InetSocketAddress
to do this might not be such a good idea. (see comments on question above)
一种可能的替代方法是使用 URL 或 URI 来打印地址字符串格式,它是更加标准化的.
One possible alternative is to use a URL or URI to print the address in string format, which is much more standardized.
另一方面,如果您想用正则表达式折磨自己...;-)
On the other hand, if you want to torture yourself with regular expressions... ;-)
IPv4:
Pattern: .*/([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+):([0-9]+)
Java constant: ".*/([0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+):([0-9]+)"
仅处理点分四进制格式的地址.无法检测到无效地址.
Handles only dotted-quad format addresses. Does not detect invalid addresses.
IPv6:
Pattern: .*/([0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+(%[a-zA-Z0-9]+)?):([0-9]+)
Java constant: ".*/([0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+:[0-9a-f]+(%[a-zA-Z0-9]+)?):([0-9]+)"
处理所有8个16位段的IPv6地址. (再次注意,这样做的唯一原因是因为Java中的Inet6Address实现似乎以非标准的方式打印地址-可能因此可以附加端口号并且没有歧义)不检测无效的IPv6地址.仅处理小写的十六进制字符.使用大写或小写字母和/或数字处理区域/范围ID(如果有).
Handles IPv6-addresses with all 8 16-bit sections. (note again that the only reason this works is because the Inet6Address implementation in Java seems to print the addresses in a non-standard way - probably so it can append the port number and there is no ambiguity) Does not detect invalid IPv6 addresses. Handles only lowercase hex characters. Handles zone/scope IDs (if present) with uppercase or lowercase letters and/or digits.
我使用方便的小程序对它们进行了测试.
记录下来,我仍然认为这是一个坏主意. ;-)我不确定是否所有的Java平台都会以这种方式打印地址.
And for the record, I still think it's a bad idea. ;-) I can't be sure if all Java platforms will print the addresses this way.
这篇关于验证InetSocketAddresses的正则表达式(ipv4/v6 +端口地址)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!