android 获取手机ip的方式

第一,通过WifiManager获取

private String getLocalIPAddress (Context context) {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            String ipAddress = FormatIP(wifiInfo.getIpAddress());
            return ipAddress;
}

public String FormatIP (int ip) {
            return Formatter.formatIpAddress(ip);
}

 

 第二,通用的方式java.net.networkinterface

private 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() && inetAddress instanceof Inet4Address) {
                            // return inetAddress.getAddress().toString();
                            return inetAddress.getHostAddress().toString();
                        }
                    }
                }
            } catch (SocketException ex) {
                Log.e("BaseScanTvDeviceClient", "获取本机IP false =" +  ex.toString());
            } 

            return null;
        }

 

 

 

 

版权声明:本文为zhangyulogin原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/zhangyulogin/archive/2012/09/16/2687313.html