VpnService.java 中的 'protect' 方法到底是做什么的

What exactly does the 'protect' method in VpnService.java

我正在经历 VpnService.java 来自 ToyVpn 项目。

我最初在 运行 方法中看到以下几行

 // Create a DatagramChannel as the VPN tunnel.
 tunnel = DatagramChannel.open();

 // Protect the tunnel before connecting to avoid loopback.
 if (!protect(tunnel.socket())) {
      throw new IllegalStateException("Cannot protect the tunnel");
 }

我知道第一行创建了一个 Datagram/UDP 通道来连接到远程服务器。但是我不明白 "protect" 方法到底在做什么。

有人可以向我解释尽可能多的技术细节。谢谢。

它是来自 android.net.VpnService library that is imported in the ToyVpnService.java class as you can see in the source code

的函数

你可以找到它的作用here

public boolean protect (int socket)

Added in API level 14

Protect a socket from VPN connections. After protecting, data sent through this socket will go directly to the underlying network, so its traffic will not be forwarded through the VPN. This method is useful if some connections need to be kept outside of VPN. For example, a VPN tunnel should protect itself if its destination is covered by VPN routes. Otherwise its outgoing packets will be sent back to the VPN interface and cause an infinite loop. This method will fail if the application is not prepared or is revoked.

The socket is NOT closed by this method.

Returns true on success.