如何获取我的IP地址?

时间:2011-08-17 00:33:24

标签: android sockets ip-address

我有一个serverSocket,我想知道IP地址,但是

listenSocket.getInetAddress().toString();

我得到 0.0.0.0 。 如何获取IP地址,或者(如果启用了两个连接)其中一个?

3 个答案:

答案 0 :(得分:15)

我过去曾用过这个:

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;
}

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

答案 1 :(得分:2)

请检查一下 How to get IP address of the device from code? 得到ipaddress也需要检查  InetAddressUtils.isIPv4Address(SADDR);

答案 2 :(得分:0)

如果你得到0.0.0.0,那可能是因为你的侦听套接字正在接受所有机器接口上的连接。通常,它们中至少有两个 - 一个用于与外界通信,以及localhost / loopback接口。因此,要求一个地址并没有明确的意义。

接受传入连接后,您可以询问处理它的特定接口的地址。

找到“好”IP地址的快速技巧是与已知站点建立传出连接,并在连接后询问其本地端的地址。这样更便携而不是枚举网络接口(如果你关心这些事情),但当然要求你有一些东西可以连接到你信任的活着和可达的东西。

相关问题