AI智能
改变未来

Android 判断网络是否可用 & 获取IP地址 & 获取以太网口MAC地址


判断网络是否可用:

注意!是判断网络是否可用,但网络可用不代表一定能上外网的!

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是指超时时间为3sProcess 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;}
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » Android 判断网络是否可用 & 获取IP地址 & 获取以太网口MAC地址