Why Inet6Address.getByAddress requires both hostname AND direct address bytes?

Vi. :

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

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

Inet6Address is supposed to hold something like sockaddr_in6 sans port number (16 address bytes plus scope_id if link-local), at least what I think of it. Given 16 bytes and scope id, I suppose that Inet6Address should be fully specified, without the need for further bits. Yet there is extra argument host...

Documentation links to explanation of InetAddr.getByAddress(String,byte[]), which also contains unclear snippet:

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.

If no DNS then why hostname is needed at all when there are already bytes supplied? Will it work with null instead of host? Why there is no getByAddress with just addr and scope_id (without host)?

Malt :

First of all, there is a factory method that takes just the byte array and does what you'd expect:

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);

However, we're interested in the hostname part, so let's read the documentation for 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.

We've built that first IP address without a hostname, so according to the javadoc, calling getHostName() will perform an actual lookup. This may or many not be what we want so java gives us a second option. If we build the address like this:

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

Then getHostName() would simply print the hostname which we gave (foo) without any lookup.

Btw, the same explanation can be found in the javadoc for InetAddress itself:

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).

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=305424&siteId=1