How to get my ip address? [duplicate]

依然范特西╮ 提交于 2019-12-21 04:19:08

问题


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.



来源:https://stackoverflow.com/questions/7086734/how-to-get-my-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!