1,424
社区成员




代码如下
APP_ID权限等设置已经打开了,在ios系统中也新建了vpn连接,但无法连接,请教大佬,有相关经验的,可否提供类似代码?
import UIKit
import NetworkExtension
@objcMembers
class ViewController: UIViewController {
@IBOutlet var connectButton: UIButton!
let vpnManager = NETunnelProviderManager.shared()
private func initVPNTunnelProviderManager() {
let tunnelProtocol = NETunnelProviderProtocol()
tunnelProtocol.providerBundleIdentifier = "com.xx.xx"
// 设置你的 hosts 或其他协议参数
tunnelProtocol.serverAddress = "223.1.1.1"
tunnelProtocol.username = "test"
if let passwordData = "test".data(using: .utf8) {
tunnelProtocol.passwordReference = passwordData
} else {
// Handle the case where conversion from string to data fails
print("Failed to convert password string to data")
}
tunnelProtocol.providerConfiguration = [
"protocol": [
"L2TP": [
"serverAddress":"223.1.1.1",
"username": "test",
"passwordReference": "test", // Data containing the password
"sharedSecretReference": "test", // Data containing the shared secret
]
]
]
vpnManager.protocolConfiguration = tunnelProtocol
vpnManager.saveToPreferences { error in
if let error = error {
print("Error saving VPN configuration: \(error.localizedDescription)")
} else {
// Configuration saved successfully
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
initVPNTunnelProviderManager()
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.VPNStatusDidChange(_:)), name: NSNotification.Name.NEVPNStatusDidChange, object: nil)
// Do any additional setup after loading the view.
}
func VPNStatusDidChange(_ notification: Notification?) {
print("VPN Status changed:")
let status = self.vpnManager.connection.status
switch status {
case .connecting:
print("Connecting...")
connectButton.setTitle("Disconnect", for: .normal)
break
case .connected:
print("Connected...")
connectButton.setTitle("Disconnect", for: .normal)
break
case .disconnecting:
print("Disconnecting...")
break
case .disconnected:
print("Disconnected...")
connectButton.setTitle("Connect", for: .normal)
break
case .invalid:
print("Invliad")
break
case .reasserting:
print("Reasserting...")
break
default:
print("unknow Vpn Status...", status)
break
}
}
@IBAction func go(_ sender: UIButton, forEvent event: UIEvent) {
print("Go!")
self.vpnManager.loadFromPreferences { (error:Error?) in
if let error = error {
print(error)
}
if (sender.title(for: .normal) == "Connect") {
do {
try self.vpnManager.connection.startVPNTunnel()
} catch {
print(error)
}
} else {
self.vpnManager.connection.stopVPNTunnel()
}
}
}
}
APP Stream IOS抓包其中一项功能就是配置hosts,我们想实现类似功能。Stream IOS抓包