2023-01-04 16:25:10
浏览数 (1)
1. 判断是否包含tun0、tun1
代码语言:javascript
复制 public void isDeviceInTun() {
try {
List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (name.equals("tun0") || name.equals("tun1")) {
Log.i("TAG", "isDeviceInVPN current device is in VPN.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
2. 获取tun0的IP地址
代码语言:javascript
复制/**
* 获取指定网卡ip地址
*
* @return
*/
public static String getLocalIP(String ethType) {
String hostIp = null;
try {
Enumeration nis = NetworkInterface.getNetworkInterfaces();
InetAddress ia = null;
while (nis.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) nis.nextElement();
if (ni.getName().equals(ethType)) {
Enumeration<InetAddress> ias = ni.getInetAddresses();
while (ias.hasMoreElements()) {
ia = ias.nextElement();
if (ia instanceof Inet6Address) {
continue;// skip ipv6
}
String ip = ia.getHostAddress();
if (!"127.0.0.1".equals(ip)) {
hostIp = ia.getHostAddress();
break;
}
}
}
}
} catch (SocketException e) {
Log.i("IPUtil", "SocketException");
e.printStackTrace();
}
return hostIp;
}