How to get my ip address? [duplicate]

2019-03-27 08:47发布

问题:

This question already has an answer here:

  • How to get IP address of the device from code? 22 answers

I've a serverSocket and I would like to know the IP address, but with

listenSocket.getInetAddress().toString();

I get 0.0.0.0 . How can I get the IP address, or (if there are two connections enabled) one of them?

回答1:

I've used this in the past:

public 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()) {
                    return inetAddress.getHostAddress();
                }
            }
        }
    } catch (SocketException ex) {
        Log.e(LOG_TAG, ex.toString());
    }
    return null;
}

Source: http://www.droidnova.com/get-the-ip-address-of-your-device,304.html



回答2:

Please check this How to get IP address of the device from code? getting ipaddress needs following check also InetAddressUtils.isIPv4Address(sAddr);



回答3:

If you get 0.0.0.0, that is probably because your listening socket is accepting connections on all of the machine's interfaces. Typically there'll be at least two of them -- one for communicating with the outside world, and the localhost/loopback interface. So it doesn't make clear sense to ask for one address for it.

Once you accept an incoming connection, you can ask it the address of the particular interface that's handling it.

A quick trick for finding a "good' IP address is to make an outgoing connection to a known site, and ask for the address of its local end once it connects. This is somewhat more portable than enumerating network interfaces (if you care about such things), but of course requires that you have something to connect to that you trust to be alive and reachable.