2013-07-24 41 views
0

我启动一个服务器套接字,并希望它监听环回地址(127.0.0.1)。该代码如下: ......为什么android上的套接字服务器总是监听IPv6?

Inet4Address address = (Inet4Address) Inet4Address.getByName("localhost"); 
TServerSocket server = new TServerSocket(new InetSocketAddress(address ,1234)); 
......... 

public class TServerSocket{ 
...... 
    public TServerSocket(InetSocketAddress bindAddr, int clientTimeout) throws    TTransportException { 
clientTimeout_ = clientTimeout; 
try { 
    serverSocket_ = new ServerSocket(); 
    serverSocket_.setReuseAddress(true); 
    serverSocket_.bind(bindAddr); 
} catch (IOException ioe) { 
    serverSocket_ = null; 
    throw new TTransportException("Could not create ServerSocket on address " +  bindAddr.toString() + "."); 
} 
    } 
    ...... 
} 

但是我发现,这个套接字开始监听IPv6地址“:FFFF:127.0.0.1”使用命令“netstat的”,并且它 导致在另一个进程(使用Python)中运行的客户端无法通过“127.0.0.1”连接到此服务器。

为什么android会自动将IPV4地址映射到IPv6地址?

+0

到底是如何,你在Android上运行的Python? –

+0

https://code.google.com/p/python-for-android/ – user2612791

+0

[为什么我的服务总是绑定到ipv6 localhost而不是ipv4?](http://stackoverflow.com/questions/8319399 /为什么 - 不,我的服务,总是绑定到IPv6的本地主机,INSTEAD-OF-IPv4)的 –

回答

0

它没有将IPv4地址映射到IPv6。 Inet4AddressInet6Address还没有实施getByName()方法,因此您实际上使用的是从InetAddress继承的方法。如果IPv4和IPv6都可以访问主机,那么大多数操作系统都会比IPv4更喜欢IPv6(所以你应该:))。您可以尝试通过InetAddress.getAllByName("localhost")获取地址数组,然后检查地址是否为Inet4Address(或其他情况下为Inet6Address)的实例,但此示例的最简单解决方案是硬编码环回地址(127.0.0.1),因为几乎没有机会它的变化。