ipv6 压缩 java,IPV6地址在Java中压缩成形式

博客内容讨论了IPv6地址的压缩规则,根据RFC5952标准,需要尽可能缩短地址并正确放置'::'符号。作者提供了一个Java正则表达式来实现这一过程,并给出了一些输入和输出示例。解决方案确保了最长连续0字段被正确缩短。
摘要由CSDN通过智能技术生成

I have used Inet6Address.getByName("2001:db8:0:0:0:0:2:1").toString() method to compress IPv6 address, and the output is 2001:db8:0:0:0:0:2:1 ,but i need 2001:db8::2:1 . , Basically the compression output should based on RFC 5952 standard , that is

1) Shorten as Much as Possible : For example, 2001:db8:0:0:0:0:2:1 must be shortened to

2001:db8::2:1.Likewise, 2001:db8::0:1 is not acceptable,

because the symbol "::" could have been used to produce a

shorter representation 2001:db8::1.

2)

3) Choice in Placement of "::" : = When there is an alternative choice in the placement of a "::", the

longest run of consecutive 16-bit 0 fields MUST be shortened (i.e.,

the sequence with three consecutive zero fields is shortened in 2001:

0:0:1:0:0:0:1). When the length of the consecutive 16-bit 0 fields

are equal (i.e., 2001:db8:0:0:1:0:0:1), the first sequence of zero

bits MUST be shortened. For example, 2001:db8::1:0:0:1 is correct

representation.

I have also checked

Is there any java library to handle this? Could anyone please help me?

Thanks in advance.

解决方案

How about this?

String resultString = subjectString.replaceAll("((?::0\\b){2,}):?(?!\\S*\\b\\1:0\\b)(\\S*)", "::$2");

Explanation without Java double-backslash hell:

( # Match and capture in backreference 1:

(?: # Match this group:

:0 # :0

\b # word boundary

){2,} # twice or more

) # End of capturing group 1

:? # Match a : if present (not at the end of the address)

(?! # Now assert that we can't match the following here:

\S* # Any non-space character sequence

\b # word boundary

\1 # the previous match

:0 # followed by another :0

\b # word boundary

) # End of lookahead. This ensures that there is not a longer

# sequence of ":0"s in this address.

(\S*) # Capture the rest of the address in backreference 2.

# This is necessary to jump over any sequences of ":0"s

# that are of the same length as the first one.

Input:

2001:db8:0:0:0:0:2:1

2001:db8:0:1:1:1:1:1

2001:0:0:1:0:0:0:1

2001:db8:0:0:1:0:0:1

2001:db8:0:0:1:0:0:0

Output:

2001:db8::2:1

2001:db8:0:1:1:1:1:1

2001:0:0:1::1

2001:db8::1:0:0:1

2001:db8:0:0:1::

(I hope the last example is correct - or is there another rule if the address ends in 0?)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值