开发者

How to get my ip address? [duplicate]

开发者 https://www.devze.com 2023-03-29 02:17 出处:网络
This question already has answers here: How to get IP address of the device from code? (31 answers) Closed 8 years ago.
This question already has answers here: How to get IP address of the device from code? (31 answers) Closed 8 years ago.

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?


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号