我正在尝试在两个 Android 设备之间创建 IPv6 TCP 连接。但是创建套接字总是失败。
如果我像这样实例化它:
Inet6Address dest = (Inet6Address) InetAddress.getByName(addressString);
Socket socket = new Socket(dest, portNumber);
我得到以下异常:
java.net.ConnectException: failed to connect to *address* (port *portNumber*): connect failed: EINVAL (Invalid argument)
如果我改为像这样实例化我的 IPv6Address 对象:
Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
NetworkInterface wifiInterface = null;
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
if (networkInterface.getDisplayName().equals("wlan0") || networkInterface.getDisplayName().equals("eth0")) {
wifiInterface = networkInterface;
break;
}
}
Inet6Address dest = Inet6Address.getByAddress(null, addressBytes, wifiInterface );
Socket socket = new Socket(dest, portNumber);
调用 Socket 构造函数时出现此错误:
java.net.ConnectException: failed to connect to *address* (port *portNumber*): connect failed: EADDRNOTAVAIL (Cannot assign requested address)
这在带有果冻 bean 的 Galaxy Nexus 和带有 Gingerbread 的 Nexus One 上都会发生。
我做错了什么吗?创建这样的套接字的正确方法是什么?
还有:This post建议使用构造函数
Inet6Address getByAddress (String host, byte[] addr, int scope_id)
在这种情况下,我必须使用什么作为 scope_id?
最佳答案
由于您的 IP 地址是本地链接,也许它必须使用范围 ID 或接口(interface)创建,以便操作系统知道将其绑定(bind)到哪个接口(interface)。至于指定 scope_id,Android 文档似乎有些欠缺。 Oracle 文档 here表示作用域 ID 是系统特定的,无法以编程方式确定。
因此,我会尝试使用替代工厂方法,您可以在其中明确指定要使用的 NetworkInterface。参见 here了解详情。 NetworkInterface 类中有一些方法可以发现系统上存在哪些接口(interface)。
关于java - Android 上的 IPv6 套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13421962/