gpt4 book ai didi

java - 为什么 Inet6Address.getByAddress 需要主机名和直接地址字节?

转载 作者:搜寻专家 更新时间:2023-11-01 02:35:08 25 4
gpt4 key购买 nike

https://docs.oracle.com/javase/7/docs/api/java/net/Inet6Address.html

public static Inet6Address getByAddress(String host,
byte[] addr,
int scope_id)

Inet6Address 应该包含诸如 sockaddr_in6 之类的东西,没有端口号(16 个地址字节加上 scope_id,如果是本地链路),至少我是这么认为的。给定 16 个字节和作用域 ID,我认为 Inet6Address 应该被完全指定,而不需要更多位。然而还有额外的参数 host...

文档链接到 InetAddr.getByAddress(String,byte[]) 的解释,其中还包含不清楚的片段:

Creates an InetAddress based on the provided host name and IP address. No name service is checked for the validity of the address.
The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address.

No validity checking is done on the host name either.

如果没有 DNS 那么为什么在已经提供了字节的情况下还需要主机名?它可以与 null 而不是 host 一起使用吗?为什么没有 getByAddress 只有 addrscope_id(没有 host)?

最佳答案

首先,有一个工厂方法只接受字节数组并执行您期望的操作:

byte[] addr = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
InetAddress ip = Inet6Address.getByAddress(addr);

但是,我们对主机名部分感兴趣,所以让我们阅读 documentation对于 getHostName():

Gets the host name for this IP address.

If this InetAddress was created with a host name, this host name will be remembered and returned;otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service.

我们已经构建了第一个没有主机名的 IP 地址,因此根据 javadoc,调用 getHostName() 将执行实际查找。这可能是也可能不是我们想要的,所以 java 给了我们第二个选择。如果我们像这样构建地址:

InetAddress ip = InetAddress.getByAddress("foo", addr);

然后 getHostName() 将简单地打印 我们 提供的主机名 (foo) 而无需任何查找。

顺便说一句,同样的解释可以在 javadoc 中找到InetAddress 本身:

An instance of an InetAddress consists of an IP address and possibly its corresponding host name (depending on whether it is constructed with a host name or whether it has already done reverse host name resolution).

关于java - 为什么 Inet6Address.getByAddress 需要主机名和直接地址字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58330485/

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