3

我使用了 NSDServiceInfo.getHost()。getHostAddress() 输出的是 IPv4 到 IPv6 的设备和路由器。对于设备,我已经可以使用 IPv4,所以我需要 IPv6。除了路由器,我已经可以了,所以我需要 IPV4 IPV6。

我尝试过的解决方案。但是当他的主机地址发出 IPV4 时,则退出错误“不是 IPv6 地址:[xx, xx, xx, xx]

同时,当它发出主机地址 IPv6 时,错误消息“java.net.Inet6Address can't be cast to java.net.Inet4Address”

我喜欢这种编码

List <NSDServiceInfo> Data = new ArrayList<>();
InetAddress hostInet =InetAddress.getByName(Data.get(position).getHost().GetHostAddress());
byte [] addressBytes = hostInet.getAddress();

Inet6Address dest6 = Inet6Address.getByAddress(Data.get(position).getHost().GetHostAddress(), addressBytes, NetworkInterface.getByInetAddress(hostInet));
Inet4Address dest4 = (Inet4Address) Inet4Address.getByAddress (Data.get(position).getHost().GetHostAddress(), addressBytes);
Log.d ( "IP", "IPv4" + dest4.getHostAddress ());
Log.d ( "IP", "IPv6:" + dest6.getHostAddress ());
4

3 回答 3

2

首先InetAddress通过给出主机名使用静态函数获取对象

InetAddress hostInet= InetAddress.getByName(hostNameString);

现在我们需要使用字节数组表示 hostInet

byte [] addressBytes = hostInet.getAddress();

现在您可以使用它addressBytes来格式化为 IPv4 或 IPv6 使用Inet6AddressInet4Address使用getByAddress加上您需要使用getByInetAddress函数传递 hostName 、字节地址和网络接口

Inet6Address dest = Inet6Address.getByAddress(hostNameString, addressBytes, NetworkInterface.getByInetAddress(hostInet));

或者

Inet4Address dest = Inet4Address.getByAddress(hostNameString, addressBytes, NetworkInterface.getByInetAddress(hostInet));

dest现在您可以使用getAddressgetHostAddress函数检索对象的文本或字节表示

于 2016-10-05T10:44:41.157 回答
1

这是我问的不完整的错。所以我使用了 NSDServiceInfo.getHost()。getHostAddress() 输出的是 IPv4 到 IPv6 的设备和路由器。对于设备,我已经可以使用 IPv4,所以我需要 IPv6。除了路由器,我已经可以了,所以我需要 IPV4 IPV6。

我尝试过的解决方案。但是当他的主机地址发出 IPV4 时,则退出错误“不是 IPv6 地址:[xx, xx, xx, xx]

同时,当它发出主机地址 IPv6 时,错误消息“java.net.Inet6Address can't be cast to java.net.Inet4Address”

我喜欢这种编码

List <NSDServiceInfo> Data = new ArrayList<>();
InetAddress hostInet =InetAddress.getByName(Data.get(position).getHost().GetHostAddress());
byte [] addressBytes = hostInet.getAddress();

Inet6Address dest6 = Inet6Address.getByAddress(Data.get(position).getHost().GetHostAddress(), addressBytes, NetworkInterface.getByInetAddress(hostInet));
Inet4Address dest4 = (Inet4Address) Inet4Address.getByAddress (Data.get(position).getHost().GetHostAddress(), addressBytes);
Log.d ( "IP", "IPv4" + dest4.getHostAddress ());
Log.d ( "IP", "IPv6:" + dest6.getHostAddress ());

对不起,如果我的英语不好,谢谢

于 2016-10-06T04:14:31.727 回答
0

NsdServiceInfo有一个java.net.InetAddressgetHostAddress()类型的方法。IP 地址的文本表示是特定于地址族的:

这两个类都扩展了InetAddress. 您需要一种public String getHostAddress()以文本形式返回 IP 地址字符串的方法。

于 2016-10-05T10:12:04.060 回答