android 获取 ip 地址方法

来源:互联网 发布:linux vim python配置 编辑:程序博客网 时间:2024/04/29 14:48
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("  ", ex.toString());    }    return null;}
实际真机测试过。但是注意链接wifi时,获取的是局域网ip。
0 0
原创粉丝点击