简单记录一下工作开发VPN程序的步骤,主要逻辑在VPNManager文件中
1、创建扩展进程
2、扩展进程处理
创建完扩展进程程序中会多出一个Tunnel/PacketTunnelProvider.swift文件
PacketTunnelProvider.swift文件中的处理
2.1、VPN开启的回调
override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) {
let tunnelNetworkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "192.168.3.14")
tunnelNetworkSettings.mtu = 1400
tunnelNetworkSettings.ipv4Settings = NEIPv4Settings(addresses: ["10.10.10.10"], subnetMasks: ["255.255.255.255"])
tunnelNetworkSettings.ipv4Settings!.includedRoutes = [NEIPv4Route.default()]
let nedn = NEDNSSettings(servers: ["223.5.5.5"])
nedn.matchDomains = [""]
tunnelNetworkSettings.dnsSettings = nedn
setTunnelNetworkSettings(tunnelNetworkSettings) { [self] error in
if error==nil {
completionHandler(nil)
readPakcets()
}else{
completionHandler(error)
}
}
}
2.2、VPN关闭的回调
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
connection?.cancel()
completionHandler()
}
2.3、网络数据的获取
func readPakcets() {
packetFlow.readPackets { [self] packets, protocols in
for packet in packets{
//这里是拦截到的网络数据,根据业务需求进行处理
//处理好的数据可以调用下边的方法重新写入手机
//packetFlow.writePackets([packet!], withProtocols: [NSNumber(value: AF_INET)])
}
readPakcets()
}
}
3、VPNManager的使用
3.1、配置VPN
func saveVPNConfig() {
VPNManager.share.delegate = self
let vpnModel = VPNConfig(tunnelBundleId: "\(Bundle.main.bundleIdentifier!).Tunnel",
serverAddress: "1010101010",
serverPort: "54345",
mtu: "1400",
ip: "10.8.0.2",
subnet: "255.255.255.0",
dns: "8.8.8.8,8.4.4.4",
vpnName: "VPNManager")
VPNManager.share.configManager(vpnModel)
}
3.2、开启VPN
VPNManager.share.startVPN()
3.3、关闭VPN
VPNManager.share.stopVPN()
3.4、VPN状态回调
func vpnStatusChange(status: NEVPNStatus) {
switch vpnStatus {
case .invalid:
print("未配置")
case .disconnected:
print("未连接")
case .connected:
print("已连接")
default:
break
}
}
Deno地址:https://github.com/YuanMingyang/VPNManager.git