NetStatusUtils.java
2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.gimi.common.cinema.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
/**
* 网络助手
* Created by 李攀 on 2015/5/14.
*/
public class NetStatusUtils {
/**
* 判断网络是否可用
* <p>需添加权限 {@code <uses-permission android:name="android.permission.INTERNET"/>}</p>
*
* @return {@code true}: 可用<br>{@code false}: 不可用
*/
public static boolean isAvailableByPing() {
return isAvailableByPing("123.125.114.144");
}
public static boolean isAvailableByPing(String ip) {
ShellUtils.CommandResult result = ShellUtils.execCommand("ping -c 1 -w 1 " + ip, false);
return result.result == 0;
}
public static boolean isNetworkConnected(Context context) {
if (context != null) {
ConnectivityManager mConnectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable();
}
}
return false;
}
public static String getIp() throws SocketException {
String ipAddress = "";
Enumeration<NetworkInterface> netInterfaces = null;
netInterfaces = NetworkInterface.getNetworkInterfaces();
if (netInterfaces == null) {
return ipAddress;
}
while (netInterfaces.hasMoreElements()) {
NetworkInterface intf = netInterfaces.nextElement();
if (intf.getName().toLowerCase().equals("eth0") || intf.getName().toLowerCase().equals("wlan0")) {
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
String curIpAddress = inetAddress.getHostAddress();
if (!curIpAddress.contains("::")) { // 过滤ipV6的地址
ipAddress = curIpAddress;
if (intf.getName().toLowerCase().equals("eth0")) {
return ipAddress;
}
}
}
}
}
}
return ipAddress;
}
}