Android上的IPv6套接字

时间:2012-11-16 17:59:24

标签: java android sockets tcp ipv6

我正在尝试在两个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)

这种情况发生在带有果冻豆的Galaxy Nexus和带有姜饼的Nexus One上。

我做错了吗?创建这样的套接字的正确方法是什么?

另外:This post建议使用构造函数

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

在这种情况下,我必须使用什么作为scope_id?

1 个答案:

答案 0 :(得分:5)

由于您的IP地址是本地链接,因此可能必须使用范围ID或接口创建,以便操作系统知道将其绑定到哪个接口。至于指定scope_id,Android文档似乎有点缺乏。 Oracle文档here表示范围ID是系统特定的,无法以编程方式确定。

因此,我会尝试使用备用工厂方法,您可以在其中明确指定要使用的NetworkInterface。有关详细信息,请参阅here。 NetworkInterface类中有一些方法可以发现系统中存在哪些接口。

相关问题