Android系统信息获取 之七:获取IP地址和MAC地址
16lz
2021-01-23
Android系统信息获取 之七:获取IP地址和MAC地址
Android系统可以通过WIFI和移动网络GPRS或者3G上网,使用不同网络上网的时候本机的IP地址并不一样。这里予以总结Android系统获取IP地址的方法和获取MAC地址的方法。
1、使用WIFI时,获取本机IP地址
很明显使用WIFI的时候,要想获取本机的IP地址是通过WIFI服务(WIFI_SERVICE)来获取的。
获取WIFI服务方法:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
获取IP地址方法:
/*** * 使用WIFI时,获取本机IP地址 * @param mContext * @return */public static String getWIFILocalIpAdress(Context mContext) { //获取wifi服务 WifiManager wifiManager = (WifiManager)mContext.getSystemService(Context.WIFI_SERVICE); //判断wifi是否开启 if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); String ip = formatIpAddress(ipAddress); return ip; } private static String formatIpAddress(int ipAdress) { return (ipAdress & 0xFF ) + "." + ((ipAdress >> 8 ) & 0xFF) + "." + ((ipAdress >> 16 ) & 0xFF) + "." + ( ipAdress >> 24 & 0xFF) ; }
这里将IP地址格式化0单独作为一个方法。 说明:如果要在应用中使用需要添加WIFI访问的相关权限:
2、获取本机MAC地址
/** * 获取MAC地址 * @param mContext * @return */public static String getMacAddress(Context mContext) {String macStr = "";WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);WifiInfo wifiInfo = wifiManager.getConnectionInfo();if (wifiInfo.getMacAddress() != null) {macStr = wifiInfo.getMacAddress();// MAC地址} else {macStr = "null";}return macStr;}
说明:获取本机MAC地址之前,需要通过WIFI连接一下网络(需要初始化硬件),才能获取到本机的MAC地址。
3、使用GPRS时,获取本机IP地址
/** * 使用GPRS时,获取本机IP地址 * @return */public static String getGPRSLocalIpAddress() {try {for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {NetworkInterface intf = en.nextElement();for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()) {return inetAddress.getHostAddress().toString();}}}} catch (SocketException ex) {Log.e("WifiPreference IpAddress", ex.toString());}return null;}
说明:如果在应用中使用时需要添加权限:
4、获取网关的IP地址
这个无论是WIFI上网或者GPRS上网,均可使用
/*** * 获取网关IP地址 * @return */public static String getHostIp() {try {for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {NetworkInterface intf = en.nextElement();for (Enumeration ipAddr = intf.getInetAddresses(); ipAddr.hasMoreElements();) {InetAddress inetAddress = ipAddr.nextElement();if (!inetAddress.isLoopbackAddress()) {return inetAddress.getHostAddress();}}}} catch (SocketException ex) {} catch (Exception e) {}return null;}
更多相关文章
- Android中Handler的使用方法——在子线程中更新界面
- Android网络编程之通过Get方法实现
- android控件的监听绑定方法
- 全面的Android文件目录解析和获取方法(包含对6.0系统的说明)
- Android官方的文档中提到了模拟器中设置代理服务器的方法,即在命
- 如何向Android的framework里添加新类 &&& android修改开放类方法
- Android swap分区作用及swapper软件设置方法
- android Matrix处理图片原理及方法整理