簡(jiǎn)單記錄一下工作開(kāi)發(fā)VPN程序的步驟,主要邏輯在VPNManager文件中
1、創(chuàng)建擴(kuò)展進(jìn)程
2、擴(kuò)展進(jìn)程處理
創(chuàng)建完擴(kuò)展進(jìn)程程序中會(huì)多出一個(gè)Tunnel/PacketTunnelProvider.swift文件
PacketTunnelProvider.swift文件中的處理
2.1盗痒、VPN開(kāi)啟的回調(diào)
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關(guān)閉的回調(diào)
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: @escaping () -> Void) {
connection?.cancel()
completionHandler()
}
2.3昔脯、網(wǎng)絡(luò)數(shù)據(jù)的獲取
func readPakcets() {
packetFlow.readPackets { [self] packets, protocols in
for packet in packets{
//這里是攔截到的網(wǎng)絡(luò)數(shù)據(jù)笑陈,根據(jù)業(yè)務(wù)需求進(jìn)行處理
//處理好的數(shù)據(jù)可以調(diào)用下邊的方法重新寫(xiě)入手機(jī)
//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廉白、開(kāi)啟VPN
VPNManager.share.startVPN()
3.3、關(guān)閉VPN
VPNManager.share.stopVPN()
3.4乖寒、VPN狀態(tài)回調(diào)
func vpnStatusChange(status: NEVPNStatus) {
switch vpnStatus {
case .invalid:
print("未配置")
case .disconnected:
print("未連接")
case .connected:
print("已連接")
default:
break
}
}
Deno地址:https://github.com/YuanMingyang/VPNManager.git