0

I start a server socket , and hope it listen on the loopback address(127.0.0.1). The code is as following: ......

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() + ".");
 }
  }
   ......
}

But I found that this socket starts to listen on an IPv6 address ":ffff:127.0.0.1" with the command "netstat", and it caused that a client running in another process(in Python) can't connect to this server through "127.0.0.1".

Why android automatically mapped an IPV4 address to an IPv6 address ?

2 Answers2

0

It didn't map IPv4 address to IPv6. Inet4Address and Inet6Address don't have implemented getByName() method so you are actually using the inherited method from InetAddress. If a host is reachable by both IPv4 and IPv6 majority of operating systems will prefer IPv6 over IPv4 (and so should you:) ). You can try getting the array of addresses by InetAddress.getAllByName("localhost") and then check if address is instance of Inet4Address (or Inet6Address in other case), but the easiest solution for this example is hardcoding the loopback address (127.0.0.1) since there is virtually no chance of it changing.

pajaja
  • 2,078
  • 4
  • 21
  • 31
0

It's not listening on an IPv6 per se, netstat (on Android) is merely printing out the IPv4 address (127.0.0.1) encoded as an IPv6 address. It does that for all sockets even when the network is IPv4 only.

More details here: http://www.tcpipguide.com/free/t_IPv6IPv4AddressEmbedding.htm

selbie
  • 82,148
  • 13
  • 83
  • 154