【问题标题】:IPv6 Socket on AndroidAndroid 上的 IPv6 套接字
【发布时间】:2012-11-05 11:53:34
【问题描述】:

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

这发生在带有 Jelly Bean 的 Galaxy Nexus 和带有 Gingerbread 的 Nexus One 上。

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

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

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

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

【问题讨论】:

  • 向我们展示 dest 和 portNumber 变量值。
  • 第一个变体中 addressString 的值例如是“fe80::9221:55ff:fee3:3303”。对应的addressBytes数组为[-2, -128, 0, 0, 0, 0, 0, 0, -110, 33, 85, -1, -2, -29, 51, 3]。对于我使用的端口 3109。这应该是一个随机端口,没有被用于其他任何东西。
  • 你连接的路由器是否支持 IPv6?
  • 我可以 ping 我所有设备的 IPv6 地址。在 Galaxy Nexus 上,NetworkInterface 对象甚至包含设备的 IPv6 地址,在 Nexus One 上,我至少可以从 /proc/net/if_inet6 读取它。所以我很确定路由器支持它:)

标签: java android sockets tcp ipv6


【解决方案1】:

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

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

【讨论】:

  • 谢谢!但这不是我在第二个变体中使用的工厂方法,它抛出的异常只是略有不同吗?
  • 你是对的!对于那个很抱歉!您是如何找到在该尝试中使用的 NetworkInterface 对象的?
  • 我遍历所有可用的接口并按名称选择我需要的接口,并验证我确实得到了正确的接口。为了清楚起见,我在原始帖子中添加了代码。
猜你喜欢
  • 1970-01-01
  • 2020-03-26
  • 2015-02-01
  • 2021-12-01
  • 2013-07-23
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 2021-12-19
相关资源
最近更新 更多