android 获取手机ip的三种方式

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

 

 

 

 

posted @ 2012-09-16 11:10  草原小狼  阅读(1947)  评论(0编辑  收藏  举报