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

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

问题描述

我正在尝试在两个Android设备之间创建IPv6 TCP连接。但是,创建套接字总是失败。

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

我收到以下异常:

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

如果我改为实例化我的IPv6Address对象:

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

调用Socket构造函数时出现此错误:

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)

在带有Jelly Bean的Galaxy Nexus和带有Gingerbread的Nexus One上都会发生这种情况。

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)

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

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

推荐答案

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

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.

因此,我会尝试使用备用工厂方法,您可以在其中明确指定要使用的NetworkInterface。参见这里了解详情。 NetworkInterface类中有一些方法可以发现系统中存在哪些接口。

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天全站免登陆