gpt4 book ai didi

java - 为什么 InetAddress.getByName ("1.2") 是有效的 ip 地址?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:07:05 24 4
gpt4 key购买 nike

public class InetAddresTest {
public static void main(String ... agrs) {
try {
InetAddress inet = InetAddress.getByName("1.2");
System.out.println("Good ip address");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

顺便说一句,InetAddress 生成的 ip 地址返回为“1.0.0.2”。我无法从 InetAddress 的 javadoc 中找到合理的答案。有人能解释一下这种行为吗?

最佳答案

来自Javadoc (链接在 Javadoc for InetAddress 中的“IP 地址的文本表示”):

When a two part address is supplied, the last part is interpreted as a 24-bit quantity and placed in the right most three bytes of the network address. This makes the two part address format convenient for specifying Class A network addresses as net.host.

编辑添加:如果 24 位部分让您感到困惑:

2 在 24 位中看起来像:00000000 00000000 00000010

然后将其映射到 IPv4 地址中右侧的 3 个八位字节为:.0.0.2

还有一个:正如 CoolBeans 在对您的问题的评论中提到的,InetAddressValidator来自 Apache commons 的文件就可以了。也就是说,如果您只想验证 IP 地址而不需要外部依赖,则可以使用 Regular Expressions to check IP addresses as well

关于java - 为什么 InetAddress.getByName ("1.2") 是有效的 ip 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9556978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com