zl程序教程

您现在的位置是:首页 >  APP

当前栏目

Android下tun0网络的检测方法

2023-02-19 12:21:24 时间

1. 判断是否包含tun0、tun1

    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地址

/**
     * 获取指定网卡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;
    }