Android 上的 IPv6 套接字 [英] IPv6 Socket on Android

查看:26
本文介绍了Android 上的 IPv6 套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am trying to create an IPv6 TCP connection between two Android devices. However creating the socket always fails.

If I instantiate it like this:

Inet6Address dest = (Inet6Address) InetAddress.getByName(addressString);
Socket socket = new Socket(dest, portNumber);

I get the following exception:

java.net.ConnectException: failed to connect to *address* (port *portNumber*): connect failed: EINVAL (Invalid argument)

If I instead instantiate my IPv6Address object like this:

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

I get this error when calling the Socket constructor:

java.net.ConnectException: failed to connect to *address* (port *portNumber*): connect failed: EADDRNOTAVAIL (Cannot assign requested address)

This happens both on a Galaxy Nexus with Jelly Bean and a Nexus One with Gingerbread.

Am I doing something wrong? What is the correct way to create a socket like that?

Also: This post suggests using the constructor

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

What would I have to use as scope_id in this case?

解决方案

Since your IP Address is link local, perhaps it MUST be created with a scope ID or Interface so that the OS knows what interface to bind it to. As for specifying the scope_id, the Android docs seem somewhat lacking. The Oracle docs here indicate that the scope ID is system specific and cannot be determined programmatically.

So, I would try using the alternate factory method where you explicitly specify the NetworkInterface you wish to use. See here for details. There are methods in the NetworkInterface class to discover what interfaces exist on the system.

这篇关于Android 上的 IPv6 套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆