[Android]获取设备IP地址

原理是遍历所有网络接口的所有IP地址。如果方法返回null,则设备没有可用的网络连接。方法返回的IP地址是设备正在使用的IP地址。

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


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


作者:黎波
博客:http://bobli.cnblogs.com/
日期:2012年3月26日
posted @ 2012-03-26 12:30  黎波  阅读(1792)  评论(0编辑  收藏  举报