首页 > 解决方案 > 连接vpn成功,手机连接不上网络

问题描述

您好,我在android上找到了一个连接vpn的示例代码,代码如下,我连接成功但手机无法访问网络?

是否有任何示例代码(或教程链接)可以在其中编辑 SNI 自定义项,例如这个HTTP Injector

VPNService.java

 void conect(){
    thread = new Thread(() -> {
    try {
        isactive=true;
        mInterface = builder.setSession("MyVPNService")
                .addAddress("192.168.2.2", 24)

                .addRoute("0.0.0.0", 0)
                .addDnsServer("8.8.8.8").establish();
        //b. Packets to be sent are queued in this input stream.
        FileInputStream in = new FileInputStream(
                mInterface.getFileDescriptor());
        //b. Packets received need to be written to this output stream.
        FileOutputStream out = new FileOutputStream(
                mInterface.getFileDescriptor());
        //c. The UDP channel can be used to pass/get ip package to/from server
        DatagramChannel tunnel = DatagramChannel.open();

        // Connect to the server, localhost is used for demonstration only.
        InetSocketAddress inetSocketAddress = new InetSocketAddress("182.xx.xx.xxx", 8080);

        tunnel.connect(inetSocketAddress);

        //d. Protect this socket, so package send by it will not be feedback to the vpn service.
        protect(tunnel.socket());
        //e. Use a loop to pass packets.
      if (tunnel.isConnected()){
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
              updateForegroundNotification("Connected"+ tunnel.getRemoteAddress());
          }
      } else {
         disconnect();
      }
      tun = tunnel;

        while (isactive){
           if(!tunnel.isConnected())
        {
                isactive=false;
                Thread.sleep(500);

            }

        }
    } catch (Exception e){
        disconnect();
        Log.e("error",e.getMessage());
    } finally {
        if (mInterface != null) {
            try {
                mInterface.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mInterface = null;
        }
    }
    });
    thread.start();
   }

标签: javaandroidvpnsniandroid-vpn-service

解决方案


推荐阅读