Android(安卓)判断网络是否可用 & 获取IP地址 & 获取以太网口MAC地址
16lz
2021-01-24
判断网络是否可用:
注意!是判断网络是否可用,但网络可用不代表一定能上外网的!
public static boolean isNetworkAvailable(Context context) { ConnectivityManager manager = (ConnectivityManager) context .getApplicationContext().getSystemService( Context.CONNECTIVITY_SERVICE); if (manager == null) { return false; } NetworkInfo networkInfo = manager.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); }
在AndroidManifest.xml文件下,添加下面权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
如果想判断是否能上外网可以ping一下外网的ip地址:
public static boolean pingIPAddress(String ipAddress) { try { //-c 1是指ping的次数为1次,-w 3是指超时时间为3s Process process = Runtime.getRuntime() .exec("ping -c 1 -w 3 " + ipAddress); //status为0表示ping成功 int status = process.waitFor(); if (status == 0) { return true; } }catch (InterruptedException | IOException e) { e.printStackTrace(); } return false; }
比如ping一下qq.com:
pingIPAddress("qq.com");
在AndroidManifest.xml文件下,添加下面权限:
<uses-permission android:name="android.permission.INTERNET"/>
获取IP地址:
public static String getHostIPAddress() { String IPAddress = null; try { Enumeration nis = NetworkInterface.getNetworkInterfaces(); while (nis.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) nis.nextElement(); Enumeration<InetAddress> ias = ni.getInetAddresses(); while (ias.hasMoreElements()) { InetAddress ia = ias.nextElement(); if (ia instanceof Inet6Address) { continue; } String hostAddress = ia.getHostAddress(); if (!"127.0.0.1".equals(hostAddress)) { IPAddress = hostAddress; break; } } } } catch (SocketException e) { e.printStackTrace(); } return IPAddress; }
在AndroidManifest.xml文件下,添加下面权限:
<uses-permission android:name="android.permission.INTERNET"/>
获取以太网口MAC地址:
public static String getEthernetMacAddress() { BufferedReader reader = null; FileReader fr = null; String ethernetMacAddress = null; try { fr = new FileReader("sys/class/net/eth0/address"); reader = new BufferedReader(fr); ethernetMacAddress = reader.readLine(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (fr != null) fr.close(); } catch (IOException e) { e.printStackTrace(); } } return ethernetMacAddress; }
更多相关文章
- android上传图片或文件
- android-1.5,1.6,2.0,2.1,2.2源码下载地址
- Android(安卓)Gradle依赖管理、去除重复依赖、忽略
- android root权限相关bin程序rageagainsttheca
- android ARM 汇编学习 —— hello world
- Android(安卓)判断Root的方法
- Android(安卓)Studio删除缓存的依赖库
- Android错误之控件FloatingActionButton
- Android实现使用流媒体播放远程mp3文件的方法