简体   繁体   中英

How do I get the IPv4 from a ServerSocket?

In my app, I create a ServerSocket , and wait for connections:

while(isRunning) {
    try {
        socket = serverSocket.accept();

I then try to get the remote IP of the resulting socket:

socket.getInetAddress().getHostAddress();

However, this seems to only return an IPv6 address.

For my purposes, I believe I need an IPv4. Is there some way to get an IPv4 address from a socket?

don't know if it's too late or not, but this little piece of code could solve your problem. I had same problem today and found this:

private String getLocalIpAddress() {
   try {
       for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
           NetworkInterface intf = en.nextElement();
           for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
               InetAddress inetAddress = enumIpAddr.nextElement();
               if (!inetAddress.isLoopbackAddress()) {
                   if (inetAddress instanceof Inet4Address) {
                       return ((Inet4Address)inetAddress).getHostAddress().toString();
                   }
               }
           }
       }
   } catch (SocketException ex) {
       Log.e("ServerActivity", ex.toString());
   }
   return null;
}

The main point is to test if IP address is really a IP V4 address.

Have fun

If the client has connected to an IPv6 address (ie, if your server is IPv6 hosted), then you'll only have the IPv6 address. You'll need to host you server in IPv4 space as well (or instead of), then have the client connect to the IPv4 address in order to get the IPv4 address of the client.

You may be able to do a lookup via DNS, but this won't be reliable (ie, do reverse lookup of IPv6 address to get hostname, then do a forward lookup, looking for A records on the host). This assumes that reverse DNS has been set up though for the address, which isn't guaranteed.

While some IPv6 addresses map to the IPv4 range it is not possible to convert all IPv6 to IPv4, as there are more IPv6 addresses than there are IPv4 addresses. Oracle has a really good document explaining IPv6 and IPv4 and how it impacts on Java and networking. You should also check out the InetAddress API document. I've linked both below:

http://docs.oracle.com/javase/1.4.2/docs/guide/net/ipv6_guide/

http://docs.oracle.com/javase/1.4.2/docs/api/java/net/InetAddress.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM