Networking

RSS for tag

Explore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.

Networking Documentation

Posts under Networking subtopic

Post

Replies

Boosts

Views

Activity

Intermittent SSL issue
Hi Team, We are getting below error when we try to connect our REST APIs from our device. Our application is enterprise application and its connecting all backend calls via MobileIron Secure Tunnel(VPN). We are not encountering this error when we try to connect backend system from Simulator on VPN connected machine. We are calling 13 APIs but we are getting below error intermittently for different APIs i.e each time we are facing this issue for different APIs. We connected with our Helpdesk team to troubleshoot the error and they checked the MobileIron VPN firewall and there is no log We configured below things Allow Arbitrary Loads - True <key>NSExceptionMinimumTLSVersion</key> <string>TLSv1.2</string> We are using Alamofire library to connect backend. We disabled all site validation and we configured minTLSVersion 1.2. Please find below code snippet static let serverTrustPolicies:[String: ServerTrustEvaluating] = { var sites = [String]() sites.append("apis.xyz.com") return sites.reduce([String: ServerTrustEvaluating]()) { (dictionary, site) -> [String: Alamofire.ServerTrustEvaluating] in var dictionary = dictionary dictionary[site] = DisabledTrustEvaluator() return dictionary } }() static let manager: Session = { var serverTrustPolicies: [String: ServerTrustEvaluating] = NetworkClient.serverTrustPolicies let configuration = URLSessionConfiguration.default configuration.tlsMinimumSupportedProtocolVersion = .TLSv12 return Alamofire.Session(configuration: configuration, serverTrustManager: CustomTrustManager(evaluators: serverTrustPolicies)) }() error from Alamofire
1
0
166
Jan ’25
Mac App Crashing
Hi, I have a problem with my Mac crashing sims 4. can you let me know if this is a Mac problem or a sims 4 problem ? Link to Mac Info : https://prnt.sc/NYG0jn8_u0dB Link to crash report : https://prnt.sc/UImzDIsqdVYn
1
0
346
Jan ’25
Usage of QUIC APIs inside HTTP/3 implementation (URLSession/Request)
Hello, I have a very basic quic client implementation. When you run this code with some basic quic server, you will see that we can't get a handle to stream identifier 0, but behavior is actually different when we use URLSession/URLRequest, and I can see that some information can be sent over the wire for stream identifier 0 with that implementation. You can find both code below I'm using to test this. I'd like to get more info about how I can use stream identifier 0 with NWMultiplexGroup, if I can't use it with NWMultiplexGroup, I need a workaround to use stream with id 0 and use multiple streams over the same connection. import Foundation import Network let dispatchQueue = DispatchQueue(label: "quicConnectionQueue") let incomingStreamQueue = DispatchQueue(label: "quicIncStreamsQueue") let outgoingStreamQueue = DispatchQueue(label: "quicOutStreamsQueue") let quicOptions = NWProtocolQUIC.Options() quicOptions.alpn = ["test"] sec_protocol_options_set_verify_block(quicOptions.securityProtocolOptions, { (sec_prot_metadata, sec_trust, complete_callback) in complete_callback(true) }, dispatchQueue) let parameters = NWParameters(quic: quicOptions); let multiplexGroup = NWMultiplexGroup(to: NWEndpoint.hostPort(host: "127.0.0.1", port: 5000)) let connectionGroup = NWConnectionGroup(with: multiplexGroup, using: parameters) connectionGroup.stateUpdateHandler = { newState in switch newState { case .ready: print("Connected using QUIC!") let _ = createNewStream(connGroup: connectionGroup, content: "First Stream") let _ = createNewStream(connGroup: connectionGroup, content: "Second Stream") break default: print("Default hit: newState: \(newState)") } } connectionGroup.newConnectionHandler = { newConnection in // Set state update handler on incoming stream newConnection.stateUpdateHandler = { newState in // Handle stream states } // Start the incoming stream newConnection.start(queue: incomingStreamQueue) } connectionGroup.start(queue: dispatchQueue) sleep(50) func createNewStream(connGroup: NWConnectionGroup, content: String) -> NWConnection? { let stream = NWConnection(from: connectionGroup) stream?.stateUpdateHandler = { streamState in switch streamState { case .ready: stream?.send(content: content.data(using: .ascii), completion: .contentProcessed({ error in print("Send completed! Error: \(String(describing: error))") })) print("Sent data!") printStreamId(stream: stream) break default: print("Default hit: streamState: \(streamState)") } } stream?.start(queue: outgoingStreamQueue) return stream } func printStreamId(stream: NWConnection?) { let streamMetadata = stream?.metadata(definition: NWProtocolQUIC.definition) as? NWProtocolQUIC.Metadata print("stream Identifier: \(String(describing: streamMetadata?.streamIdentifier))") } URLSession/URLRequest code: import Foundation var networkManager = NetworkManager() networkManager.testHTTP3Request() sleep(5) class NetworkManager: NSObject, URLSessionDataDelegate { private var session: URLSession! private var operationQueue = OperationQueue() func testHTTP3Request() { if self.session == nil { let config = URLSessionConfiguration.default config.requestCachePolicy = .reloadIgnoringLocalCacheData self.session = URLSession(configuration: config, delegate: self, delegateQueue: operationQueue) } let urlStr = "https://localhost:5000" let url = URL(string: urlStr)! var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0) request.assumesHTTP3Capable = true self.session.dataTask(with: request) { (data, response, error) in if let error = error as NSError? { print("task transport error \(error.domain) / \(error.code)") return } guard let data = data, let response = response as? HTTPURLResponse else { print("task response is invalid") return } guard 200 ..< 300 ~= response.statusCode else { print("task response status code is invalid; received \(response.statusCode), but expected 2xx") return } print("task finished with status \(response.statusCode), bytes \(data.count)") }.resume() } } extension NetworkManager { func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { let protocols = metrics.transactionMetrics.map { $0.networkProtocolName ?? "-" } print("protocols: \(protocols)") } func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { if challenge.protectionSpace.serverTrust == nil { completionHandler(.useCredential, nil) } else { let trust: SecTrust = challenge.protectionSpace.serverTrust! let credential = URLCredential(trust: trust) completionHandler(.useCredential, credential) } } }
0
0
414
Nov ’24
Issue with Multicast Message Port in NWConnectionGroup and BSD Sockets
Hello Everyone, I'm currently working on a cross-platform application that uses IP-based multicast for device discovery across both Apple and non-Apple devices running the same app. All devices join a multicast group "X.X.X.X" on port Y. For Apple devices, I am using NWConnectionGroup for multicast discovery, while for non-Apple devices, I am using BSD sockets. The issue arises when I attempt to send a multicast message to the group using NWConnectionGroup. The message is sent from a separate ephemeral port rather than the multicast port Y. As a result, all Apple processes that are using NWConnectionGroup can successfully receive the multicast message. However, the processes running on the non-Apple devices (using BSD sockets) do not receive the message. My Questions: Is there a way to configure NWConnectionGroup to send multicast messages from the same multicast port Y rather than an ephemeral port? Is there any known behavior or limitation in how NWConnectionGroup handles multicast that could explain why non-Apple devices using BSD sockets cannot receive the message? How can I ensure cross-platform multicast compatibility between Apple devices using NWConnectionGroup and non-Apple devices using BSD sockets? Any guidance or suggestions would be greatly appreciated! Thanks, Harshal
1
0
334
Dec ’24
Symbol not found error running Message Filter Extension on iOS 17.6.1 but no problem with iOS 18.2
If I run an app with a Message Filter Extension on a handset with iOS 18.2 then it runs fine, however if I run the exact same app with no changes on a different phone which has iOS 17.6.1 installed then the following error occurs when the extension is enabled within Settings: dyld[631]: Symbol not found: _$sSo40ILMessageFilterCapabilitiesQueryResponseC14IdentityLookupE21promotionalSubActionsSaySo0abI6ActionVGvs
0
0
459
Dec ’24
Issue with WebSocket Secure (wss) connection on iOS (works on Node.js, fails on iOS app)
Hello everyone, I’m developing an iOS application that uses WebSocket Secure (wss) to connect to a backend server, which is working correctly. The server is hosted on Render.com and accepts connections over https and wss. Context: • I can connect to the backend without issues using HTTPS from both the app and a web browser. • Using Node.js and the Socket.IO client, the WebSocket connection to the server works correctly over wss://. • The server is configured with a valid SSL certificate (the HTTPS connection is verified and works in a browser). • The problem occurs when I try to connect from the iOS client (using Socket.IO in Swift) to the server through wss://social-gamer-backend.onrender.com. The connection consistently fails on iOS. The Issue: Even though the URL is correctly configured, and I can connect via Node.js, when I attempt to connect from the iOS app, I get connection-related errors. The most common error is: Error while connecting to the socket: Tried emitting when not connected • The server URL is correct (wss://social-gamer-backend.onrender.com). • The JWT token is being sent correctly in the headers. • There are no visible SSL certificate issues since the HTTPS connection works fine. • I’ve tried enabling and disabling App Transport Security (ATS) in the Info.plist. • From Node.js, the same connection code works fine, indicating that the WebSocket server is active and operational. Current iOS Configuration: let manager = SocketManager(socketURL: url, config: [ .log(true), .compress, .reconnects(true), .forceWebsockets(true), .extraHeaders(["Authorization": "Bearer (token)"]) ]) What I’ve tried so far: 1. I’ve tested the connection on different networks, including Wi-Fi and mobile data. 2. I’ve checked the iOS device restrictions and disabled potential network limitations. 3. I’ve enabled detailed logs in Crashlytics, but I can’t find any relevant information indicating why the connection is failing. 4. The same URL with wss:// works on Node.js, so it’s not an issue with the WebSocket server. Question: What could be preventing the iOS app from establishing a successful connection to the WebSocket server over wss://? Is there anything else I should configure in the app or server to allow iOS to handle secure WebSocket connections? I would appreciate any help or suggestions to resolve this issue. Thank you in advance.
1
0
743
Oct ’24
setTunnelNetworkSettings() is not setting excludedRoutes
We are using PacketTunnel as system extension to establish vpn tunnel. The flow is like: Create a PacketTunnelProvide to establish vpn When tunnel gets connected add excludedRoutes by calling setTunnelNetworkSettings(). Result: The routing table is not getting updated with new excludeRoutes entries. As per setTunnelNetworkSettings() documentation: "This function is called by tunnel provider implementations to set the network settings of the tunnel, including IP routes, DNS servers, and virtual interface addresses depending on the tunnel type. Subclasses should not override this method. This method can be called multiple times during the lifetime of a particular tunnel. It is not necessary to call this function with nil to clear out the existing settings before calling this function with a non-nil configuration." So we believe setTunnelNetworkSettings() should be able to set new excludeRoutes. We could see we are passing correct entries to setTunnelNetworkSettings(): { tunnelRemoteAddress = 10.192.229.240 DNSSettings = { protocol = cleartext server = ( 10.192.230.211, 192.168.180.15, ) matchDomains = ( , ) matchDomainsNoSearch = NO } IPv4Settings = { configMethod = manual addresses = ( 100.100.100.17, ) subnetMasks = ( 255.255.255.255, ) includedRoutes = ( { destinationAddress = 1.1.1.1 destinationSubnetMask = 255.255.255.255 gatewayAddress = 100.100.100.17 }, { destinationAddress = 2.2.2.0 destinationSubnetMask = 255.255.255.255 gatewayAddress = 100.100.100.17 }, { destinationAddress = 11.11.11.0 destinationSubnetMask = 255.255.255.0 gatewayAddress = 100.100.100.17 }, ) excludedRoutes = ( { destinationAddress = 170.114.52.2 destinationSubnetMask = 255.255.255.255 }, ) overridePrimary = NO } MTU = 1298 } The problem is present on macOS Sequoia 15.2. Is it a known issue? Did anyone else faced this issue?
0
0
461
Dec ’24
What does iOS do wrt Shared Web Credentials when it makes a call to a server to perform a message filter request
In order to create a Message Filter Extension it is necessary to set up Shared Web Credentials. I'd like to form an understanding of what role SWC plays when the OS is making request to the associated network service (when the extension has called deferQueryRequestToNetwork()) and how this differs from when an app directly uses Shared Web Credentials itself. When an app is making direct use of SWC, it makes a request to obtain the user's credentials from the web site. However in the case of a Message Filter Extension, there aren't any individual user credentials, so what is happening behind the scenes when the OS makes a server request on behalf of a Message Filtering Extension? A more general question - the documentation for Shared Web Credentials says "Associated domains establish a secure association between domains and your app.". Thank you
2
0
407
Apr ’25
Can a Message Filter Extension specify more than ILMessageFilterExtensionNetworkURL or switch which is used?
I asked this question of AI and it said that yes it was possible, and gave some sample code override class func filterConfiguration() -> ILMessageFilterExtensionConfiguration { let config = ILMessageFilterExtensionConfiguration() // You can specify multiple network URLs config.networkURLs = [ URL(string: "https://api1.example.com/filter")!, URL(string: "https://api2.example.com/filter")! ] return config } And said the OS will try the first, and if there's no response within the first few seconds it'll move onto the second. However, there is no such class as ILMessageFilterExtensionConfiguration AFAICT, if there is then how to access/use it, if there isn't, then I wonder how the AI counjured it up? If multiple urls can be specified, then can the extension also specify a particular API to use and switch between them at some point? When does the OS call filterConfiguration()?
0
0
395
Dec ’24
Allow network access in tvOS app
I have a TVML style app on the app store that no longer seems to work. I'm working on converting it to SwiftUI after seeing the WWDC video "Migrate your TVML app to SwiftUI". I've got most of the code working up until I'm trying to display video from a remote source (my website). It looks like the network connection is blocked, maybe. On a macOS app I see a App Sandbox capabilities that include Network access. I don't see that option for the tvOS app. Am I missing something or is it not needed, and I should look elsewhere? Thanks, David
1
0
523
Dec ’24
About ipv6 support (gateway.icloud.com.cn/gsa.apple.com)
We are developing an iOS app and are using Firebase's Auth module. During IPv6 network testing, we found that the app fails when calling Apple's login authorization in an IPv6 environment. After investigation, we confirmed that the following two API calls: https://gateway.icloud.com.cn:443/ckdatabase/api/client/record/save https://gsa.apple.com/grandslam/GsService2 remain in a pending state. We tested gateway.icloud.com.cn and gsa.apple.com and found that these two domains do not support IPv6 DNS. What we would like to understand is whether these two domains truly do not support IPv6 DNS, and how we can implement Apple's login authorization in an IPv6 environment.
2
0
1.1k
Oct ’24
How can I get WiFi SSID in Mac Catalyst?
I just want Mac Catalyst app can look up the SSID of the currently connected WiFI. Xcode returns I can't use CoreWLan in Mac Catalyst, so I used NEHotspotNetwork, although I do not have convince whether Mac Catalyst allows it. The same code of destination works fine on iPhone, but not on Mac Catalyst and Mac(Designed for iPad). What is the proper way to get SSID of WiFI in Mac Catalyst? Is there another way to do this? The code I tried is below and I used CoreLocation API before call this function. func getWiFiSsid() { NEHotspotNetwork.fetchCurrent { network in if let network = network { print(network) } else { print("network is nil!") } } } Below is Entitlement file. Entitlements for app sandbox is removed when I run in Mac(Designed for iPad). <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.developer.networking.HotspotConfiguration</key> <true/> <key>com.apple.developer.networking.networkextension</key> <array/> <key>com.apple.developer.networking.wifi-info</key> <true/> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.network.client</key> <true/> <key>com.apple.security.network.server</key> <true/> <key>com.apple.security.personal-information.location</key> <true/> </dict> </plist> Below is Info.plist file. <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>$(DEVELOPMENT_LANGUAGE)</string> <key>CFBundleExecutable</key> <string>$(EXECUTABLE_NAME)</string> <key>CFBundleIdentifier</key> <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>$(PRODUCT_NAME)</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1</string> <key>LSRequiresIPhoneOS</key> <true/> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>UISupportedInterfaceOrientations~ipad</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationPortraitUpsideDown</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>NSLocationUsageDescription</key> <string>Determine whether the ssid of current Wi-Fi connection</string> <key>NSLocationWhenInUseUsageDescription</key> <string>Determine whether the ssid of current Wi-Fi connection</string> </dict> </plist> The console log is below. NEHotspotNetwork nehelper sent invalid result code [1] for Wi-Fi information request
1
0
624
Dec ’24
Network Extension Resources
https://developer.apple.com/forums/thread/707294 General: Forums subtopic: App & System Services > Networking DevForums tag: Network Extension Network Extension framework documentation Routing your VPN network traffic article Filtering traffic by URL sample code Filtering Network Traffic sample code TN3120 Expected use cases for Network Extension packet tunnel providers technote TN3134 Network Extension provider deployment technote TN3165 Packet Filter is not API technote Network Extension and VPN Glossary forums post Debugging a Network Extension Provider forums post Exporting a Developer ID Network Extension forums post Network Extension vs ad hoc techniques on macOS forums post Network Extension Provider Packaging forums post NWEndpoint History and Advice forums post Extra-ordinary Networking forums post Wi-Fi management: Wi-Fi Fundamentals forums post TN3111 iOS Wi-Fi API overview technote How to modernize your captive network developer news post iOS Network Signal Strength forums post See also Networking Resources. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
2.7k
2d
Cannot open Chrome UDP flows in Transparent Proxy Provider
We are implementing a Transparent Proxy for HTTPS (via TCP and QUIC). The following rules are set in startProxy: settings.includedNetworkRules = [ NENetworkRule(destinationNetwork: NWHostEndpoint(hostname: "0.0.0.0", port: "443"), prefix: 0, protocol: .TCP), NENetworkRule(destinationNetwork: NWHostEndpoint(hostname: "::", port: "443"), prefix: 0, protocol: .TCP), NENetworkRule(destinationNetwork: NWHostEndpoint(hostname: "0.0.0.0", port: "443"), prefix: 0, protocol: .UDP), NENetworkRule(destinationNetwork: NWHostEndpoint(hostname: "::", port: "443"), prefix: 0, protocol: .UDP) ] Handling TCP connections seems to work fine. But opening UDP flows from Chrome (or Brave) always fails with Error Domain=NEAppProxyFlowErrorDomain Code=2 "The peer closed the flow" (Doing the same for Firefox works!) BTW: We first create a remote UDP connection (using the Network framework) and when it is in the ready state, we use connection?.currentPath?.localEndpoint as the localEndpoint parameter in the open method of the flow. Is it a known issue that QUIC connections from Chrome cannot be handled by a Transparent Proxy Provider?
3
0
480
Dec ’24
How can I control if traffic from other apps goes through the proxy when using a NETunnelProvider?
I am setting up a fake VPN with proxy settings using NEPacketTunnelProvider. When I check proxy check sites, I can see the proxy is detected. let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "10.0.0.1") let proxySettings = NEProxySettings() proxySettings.httpEnabled = true proxySettings.httpsEnabled = true proxySettings.httpServer = NEProxyServer(address: hostIP, port: portNumber) proxySettings.httpsServer = NEProxyServer(address: hostIP2, port: portNumber2) proxySettings.excludeSimpleHostnames = false proxySettings.matchDomains = [""] settings.proxySettings = proxySettings How can I control whether other installed apps on the phone use or bypass this proxy? Can I do this with exceptionList? Since I am routing everything through a VPN, I assumed I could control this. The selection of which apps use the proxy should be up to the user. Could you provide an explanation of how I can manage this? I am quite new to these types of tasks.
1
0
242
Dec ’24
NEPacketTunnelProvider - Tunnel Works but Internet Connection Fails
Hi, I'm working on a VPN app using NEPacketTunnelProvider. The primary goal is to capture outgoing network packets while keeping the internet connection functional. However, with the current implementation, the internet connection stops working after the VPN is enabled. Specifically, browsers like Safari and Chrome fail to load any website (e.g., google.com or apple.com). Below is the relevant code snippet from my startTunnel method: override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { os_log("Starting tunnel...", log: self.log, type: .info) // Configure network settings let networkSettings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "10.0.0.1") networkSettings.ipv4Settings = NEIPv4Settings(addresses: ["10.0.0.2"], subnetMasks: ["255.255.255.0"]) networkSettings.ipv4Settings?.includedRoutes = [NEIPv4Route.default()] // Route all traffic through tunnel networkSettings.ipv4Settings?.excludedRoutes = [] // No exceptions // DNS configuration networkSettings.dnsSettings = NEDNSSettings(servers: ["8.8.8.8"]) //networkSettings.dnsSettings?.matchDomains = [""] // Uncommented to process all domains // MTU configuration networkSettings.mtu = 1400 // Apply tunnel network settings setTunnelNetworkSettings(networkSettings) { [weak self] error in guard let self = self else { return } if let error = error { os_log("Failed to set tunnel settings: %{public}@", log: self.log, type: .error, error.localizedDescription) completionHandler(error) return } os_log("Tunnel settings applied successfully", log: self.log, type: .info) self.readPackets() // Start reading packets completionHandler(nil) } } private func readPackets() { let queue = DispatchQueue(label: "PacketProcessing", qos: .userInitiated) self.packetFlow.readPackets { packets, protocols in queue.async { for (i, packet) in packets.enumerated() { self.logPacketInfo(packet: packet, protocolCheck: Int32(protocols[i])) self.packetFlow.writePackets([packet], withProtocols: [protocols[i]]) // Re-send packet } self.readPackets() // Continue reading } } } Questions Are there additional configurations required to ensure that the VPN forwards packets correctly to maintain internet connectivity? Could there be a missing setting related to includedRoutes or dnsSettings that is causing the issue? How should packets be properly handled in the readPackets method to avoid breaking the internet connection? With this approach, is it possible to read network packets generated by browsers like Safari and Chrome? Please understand that it's my first time leaving a question, so it's not readable. Thank you!!
1
0
273
Dec ’24
Routing packets using Packet Tunnel Provider
Hi! I am new to Apple app development so please bear with me. I am trying to design an app that can mimic some of the functionality of iptables routing. The crux of it is I would like to redirect local traffic bound for a specific port to a different port and then redirect any outgoing traffic on that port back to the original port: outgoing packet bound for IP:1234 -> 127.0.0.1:2345 outgoing packet bound for IP:2345 -> IP:1234 I tried to implement this behavior with a packet tunnel but have not made any substantial progress. Is this the right approach? Here is my implementation: private func handleConnection(_ connection: NWConnection) { connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [weak self] data, context, isComplete, error in if let data = data, !data.isEmpty { self?.processData(data, from: connection) } if let error = error { print("Connection error: \(error)") } if isComplete { connection.cancel() } else { self?.handleConnection(connection) // Continue to receive data } } connection.start(queue: .main) } private func processData(_ data: Data, from connection: NWConnection) { switch connection.endpoint { case .hostPort(let host, let port): let portNumber = port.rawValue let hostDescription = host.debugDescription print("Received data from host: \(hostDescription) on port: \(portNumber)") if portNumber == 1234 { // Rule 1: Redirect traffic from port 1234 to 127.0.0.1:2345 redirectTraffic(data, to: "127.0.0.1", port: 2345) print("Redirecting traffic from 1234 to 2345") } else if portNumber == 2345 { // Rule 2: Redirect traffic from port 2345 to the original IP address but port 1234 redirectTraffic(data, to: hostDescription, port: 1234) print("Redirecting traffic from 2345 back to 1234") } case .service(name: _, type: _, domain: _, interface: _): print("Received bonjour service") case .unix(path: _): print("Received unix domain path") case .url(_): print("Received url") case .opaque(_): print("Opaque?") @unknown default: fatalError("Unknown endpoint type") } }
1
0
314
Sep ’24