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

Post

Replies

Boosts

Views

Activity

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
211
3w
Is this technical solution reasonable about WKWebView on Cross-domain issues ?
Is this technical solution reasonable about WKWebView on cross-domain issues ? Hi,all My project use WKWebView to load offline package, such as .html/.css/.js,and also request some resources from remote server to update pages. So there is a cross-domain problem with local file(file://***) and remote domain (https://***), is this following technical solution reasonable to fix this problem: 1. Create a custom URLSchemeHandler which conforms to WKURLSchemeHandler 2.Unify local file and remote domain request to https request 3. Hook WKWebView https request 4. Implement WKURLSchemeHandler delegate method (void)webView:(WKWebView *)webView startURLSchemeTask:(id)urlSchemeTask { NSURL *url = urlSchemeTask.request.URL; if ([url.pathExtension isEqualToString:@"html"]) { NSData *data = [[NSData alloc] initWithContentsOfFile:localFilePath]; NSMutableDictionary resHeader = [NSMutableDictionary new]; [resHeader setValue:@"" forKey:@"Access-Control-Allow-Origin"]; [resHeader setValue:@"charset=UTF-8" forKey:@"Content-Type"]; [resHeader setValue:@"text/html" forKey:@"Content-Type"]; NSHTTPURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:url statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:resHeader]; [urlSchemeTask didReceiveResponse:response]; [urlSchemeTask didReceiveData:data]; [urlSchemeTask didFinish]; } else { NSURLSession *defaultSession = [NSURLSession sharedSession]; NSURLSessionTask *dataTask = [defaultSession dataTaskWithRequest:urlSchemeTask.request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { [urlSchemeTask didReceiveResponse:response]; [urlSchemeTask didReceiveData:data]; [urlSchemeTask didFinish]; }]; [dataTask resume]; } } Is this technical solution reasonable? and is there any issues that I haven't considered? Sincerely, Looking forward to your reply
0
0
137
3w
Add "local network access" permission for macOS 15 runners
Hi, We have an issue (https://github.com/actions/runner-images/issues/10924) raised by a user requesting to add 'local network access' permission for macOS 15 and macOS 15-arm64 image runners. Apple introduced a new LNP policy with macOS Sequoia that is not controlled by TCC or MDM. Could you please guide us on how to add 'local network access' permission for macOS 15 and macOS 15-arm64 image runners? Thanks.
5
0
335
4w
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
221
3w
Reachability behaviour changed with Sonoma 14.2b
Hi, I'm looking for feedback regarding SCNetworkReachability under macOS Sonoma. It seems that since beta 3 the notifications behaviour changed. In a LaunchAgent I'm using SCNetworkReachabilityCreateWithName + SCNetworkReachabilitySetCallback + SCNetworkReachabilityScheduleWithRunLoop and wait for callbacks looking at the kSCNetworkReachabilityFlagsReachable flag. This is running fine under macOS 12.x, 13.x and 14.0 for more than a year. If I log all callback entries I observe unexpected notifications as if the looked host became unreachable for very small amount of time (ms). The host is flagged as unreachable then few ms later reachable again then unreachable again. Fast switching is fine, I can accept that the service is unreachable even for 1s but the probleme is the latest status do not reflect actual reachability of the service. This is in a corporate network with the complexity of using a proxy.pac. Does anybody noticed something similar ? I filled a Feedback FB13442134 in case it could be a regression of 14.2
3
0
702
Dec ’23
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
143
3w
Peek data of TCPFlow in transparent proxy on macOS
We are developing a tunnel based on transparent proxy system extension. We want to be able to decide whether to handle certain TCP flows based on FQDN. So, is there a way to peek into TCPFlow data like we can in ContentFilter which will allow use to parse and check for SNI or Host-header? As far as I understand, we can read data from flows until we have returned a decision from handleNewFlow.
3
0
236
3w
URLSession: The network connection was lost.
I'm seeing behaviour that I'm struggling to work out when making GraphQL related network requests (these are POST requests). I note that QA1941 covers the "lost connection" errors that I see in my responses, but I'd like to understand more, because just retrying the connection without understanding why I need to seems problematic. Here's the (partially redacted) logs I see when the error occurs: quic_conn_keepalive_handler [C69.1.1.1:2] [-0178f8467262b9e978791446c6629ddb66b2efc1] keep-alive timer fired, exceeding 2 outstanding keep-alives nw_read_request_report [C69] Receive failed with error "Operation timed out" nw_read_request_report [C69] Receive failed with error "Operation timed out" nw_read_request_report [C69] Receive failed with error "Operation timed out" nw_read_request_report [C69] Receive failed with error "Operation timed out" nw_read_request_report [C69] Receive failed with error "Operation timed out" 0x16264d818 69 stalled, attempting fallback Task <A6CC8D4D-83E1-4C61-96C7-BDDF2F04A35F>.<11> HTTP load failed, 1822/0 bytes (error code: -1005 [4:-4]) Task <3B0AAA67-3162-4F80-A930-D93F8A7EF1A4>.<12> HTTP load failed, 1823/0 bytes (error code: -1005 [4:-4]) nw_endpoint_flow_fillout_data_transfer_snapshot copy_info() returned NULL Task <A6CC8D4D-83E1-4C61-96C7-BDDF2F04A35F>.<11> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x60000139bd50 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x60000a217340 [0x1e006f658]>{length = 16, capacity = 16, bytes = 0x100201bb646394820000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <A6CC8D4D-83E1-4C61-96C7-BDDF2F04A35F>.<11>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <A6CC8D4D-83E1-4C61-96C7-BDDF2F04A35F>.<11>" ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://myserver.com/graphql, NSErrorFailingURLKey=https://myserver.com/graphql, _kCFStreamErrorDomainKey=4} Task <3B0AAA67-3162-4F80-A930-D93F8A7EF1A4>.<12> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x60000139afd0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x60000a217340 [0x1e006f658]>{length = 16, capacity = 16, bytes = 0x100201bb646394820000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3B0AAA67-3162-4F80-A930-D93F8A7EF1A4>.<12>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <3B0AAA67-3162-4F80-A930-D93F8A7EF1A4>.<12>" ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://myserver.com/graphql, NSErrorFailingURLKey=https://myserver.com/graphql, _kCFStreamErrorDomainKey=4} GraphQL request query failed for query with hash: 6677767707705440859 with error: Networking.NetworkGraphQLService.Error.underlying(Apollo.URLSessionClient.URLSessionClientError.networkError(data: 0 bytes, response: nil, underlying: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x60000139afd0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x60000a217340 [0x1e006f658]>{length = 16, capacity = 16, bytes = 0x100201bb646394820000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <3B0AAA67-3162-4F80-A930-D93F8A7EF1A4>.<12>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <3B0AAA67-3162-4F80-A930-D93F8A7EF1A4>.<12>" ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://myserver.com/graphql, NSErrorFailingURLKey=https://myserver.com/graphql, _kCFStreamErrorDomainKey=4})) GraphQL request query failed for query with hash: 148576198322832328 with error: Networking.NetworkGraphQLService.Error.underlying(Apollo.URLSessionClient.URLSessionClientError.networkError(data: 0 bytes, response: nil, underlying: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x60000139bd50 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x60000a217340 [0x1e006f658]>{length = 16, capacity = 16, bytes = 0x100201bb646394820000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <A6CC8D4D-83E1-4C61-96C7-BDDF2F04A35F>.<11>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalDataTask <A6CC8D4D-83E1-4C61-96C7-BDDF2F04A35F>.<11>" ), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=https://myserver.com/graphql, NSErrorFailingURLKey=https://myserver.com/graphql, _kCFStreamErrorDomainKey=4})) GraphQL request query starting for query with hash: -5824714640174886330 nw_connection_copy_connected_local_endpoint_block_invoke [C90] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C90] Connection has no local endpoint GraphQL request query succeeded for query with hash: -5824714640174886330 nw_read_request_report [C43] Receive failed with error "Operation timed out" nw_read_request_report [C43] Receive failed with error "Operation timed out" nw_read_request_report [C43] Receive failed with error "Operation timed out" nw_connection_add_timestamp_locked_on_nw_queue [C43] Hit maximum timestamp count, will start dropping events nw_endpoint_flow_fillout_data_transfer_snapshot copy_info() returned NULL I'd really appreciate any advice or insight that people might have — I can't reproduce this problem consistently, so I want to know more. Thanks!
4
0
333
Nov ’24
Outgoing SSL connections fail on macOS 15, work fine on earlier versions
The OpenSSL library interface to Allegro Common Lisp system stopped working with macOS 15.x (15.0.1 and 15.1). We have tried many versions of OpenSSL. 1.1.1t (which we built ourselves), 3.0.x, 3.3.x, 3.4.0. All work fine on macOS 14 and earlier. All fail on macOS 15. What is bizarre about the failure: we can load the SSL libraries fine, but when we try to make an outgoing connection it fails (with varying errors). Also, trying to use lldb to debug just hangs, once we step into the SSL libraries. More specifically, using Homebrew OpenSSL 3.0.15 gives an exception that we see in lldb, but we cannot step into SSL_ctrl(), which is in libssl.3.dylib, provided by Homebrew. We have also tried a version of OpenSSL 1.1.1t that we built ourselves (and codesigned and is included in the notarized app), and it fails with a SEGV, rather than the error below, which is using 3.0.15: What started this were errors using the OpenSSL libraries. Here's the use case: cl-user(2): (net.aserve.client:do-http-request "https://franz.com") (net.aserve.client:do-http-request "https://franz.com") Error: Received signal number 0 [condition type: synchronous-operating-system-signal] Restart actions (select using :continue): 0: Return to Top Level (an "abort" restart). 1: Abort entirely from this (lisp) process. [1] cl-user(3): :zo :all t :count 5 :zo :all t :count 5 Evaluation stack: ... 5 more newer frames ... (excl::SSL_ctrl 6133462816 55 ...) (excl::ssl-device-open-common #<excl::ssl-client-stream closed fd # @ #x3079fed32> nil ...) ->((method device-open (excl::ssl-client-stream t t)) #<excl::ssl-client-stream closed fd # @ #x3079fed32> t ...) ((:internal (:effective-method 3 nil nil nil t) 0) #<excl::ssl-client-stream closed fd # @ #x3079fed32> t ...) ((:runsys sys::lisp_apply)) [... excl::function_lisp_apply ] (excl::caching-miss #<standard-generic-function device-open> (# t #) ...) [... device-open ] ... more older frames ... [1] cl-user(4): If you want to see the problem for yourself, I created a new, signed and notarized version of our application https://franz.com/ftp/pri/layer/acl11.0express-macos-arm64.dmg. To use it, install Homebrew and do brew install openssl@3.0, then execute the following to get the error: cd /Applications/AllegroCL64express.app/Contents/Resources env ACL_OPENSSL_VERSION=30 DYLD_LIBRARY_PATH="$(brew --prefix openssl@3.0)/lib:$DYLD_LIBRARY_PATH" ./alisp (progn (require :ssl)(require :aserve)) (net.aserve.client:do-http-request "https://franz.com") You should get the error shown above. Here's what we see when we set a breakpoint at SSL_ctrl: lldb alisp _regexp-env ACL_OPENSSL_VERSION=30 _regexp-env DYLD_LIBRARY_PATH=/opt/homebrew/opt/openssl@3.0/lib: br s -n SSL_ctrl run (progn (require :ssl)(require :aserve)) (net.aserve.client:do-http-request "https://franz.com") Then, we see this: cl-user(2): (net.aserve.client:do-http-request "https://franz.com") (net.aserve.client:do-http-request "https://franz.com") Process 5886 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.2 frame #0: 0x0000000102081090 libssl.3.dylib`SSL_ctrl libssl.3.dylib`SSL_ctrl: -> 0x102081090 <+0>: stp x20, x19, [sp, #-0x20]! 0x102081094 <+4>: stp x29, x30, [sp, #0x10] 0x102081098 <+8>: add x29, sp, #0x10 0x10208109c <+12>: mov x20, x2 (lldb) si <<<hang here>>> Again, it only started with macOS 15. We have not seen this on any previous version. More detail: $ codesign -vvvv /Applications/AllegroCL64express.app /Applications/AllegroCL64express.app: valid on disk /Applications/AllegroCL64express.app: satisfies its Designated Requirement $ $ codesign -d --entitlements - /Applications/AllegroCL64express.app Executable=/Applications/AllegroCL64express.app/Contents/MacOS/AllegroCL64express [Dict] [Key] com.apple.security.cs.allow-dyld-environment-variables [Value] [Bool] true [Key] com.apple.security.cs.allow-jit [Value] [Bool] true [Key] com.apple.security.cs.disable-library-validation [Value] [Bool] true [Key] com.apple.security.get-task-allow [Value] [Bool] true $ The other thing we noticed in debugging this is even though we set DYLD_LIBRARY_PATH, another libssl seemed to be found by lldb. For example, in this case 3 versions of SSL_new were found by lldb: $ lldb alisp (lldb) target create "alisp" Current executable set to '/Applications/AllegroCL64express.app/Contents/Resources/alisp' (arm64). (lldb) _regexp-env ACL_OPENSSL_VERSION=30 (lldb) _regexp-env DYLD_LIBRARY_PATH=/opt/homebrew/opt/openssl@3.0/lib: (lldb) br s -n SSL_new br s -n SSL_new Breakpoint 1: 2 locations. (lldb) run Process 6339 launched: '/Applications/AllegroCL64express.app/Contents/Resources/alisp' (arm64) Copyright (C) 1985-2023, Franz Inc., Lafayette, CA, USA. All Rights Reserved. ... CL-USER(1): (progn (require :ssl)(require :aserve)) ; Fast loading ; /Applications/AllegroCL64express.app/Contents/Resources/code/SSL.002 ... T CL-USER(2): (net.aserve.client:do-http-request "https://franz.com") Process 6339 stopped * thread #1, queue = 'com.apple.main-thread', stop reason = breakpoint 1.3 frame #0: 0x00000001020803ec libssl.3.dylib`SSL_new libssl.3.dylib`SSL_new: -> 0x1020803ec <+0>: stp x20, x19, [sp, #-0x20]! 0x1020803f0 <+4>: stp x29, x30, [sp, #0x10] 0x1020803f4 <+8>: add x29, sp, #0x10 0x1020803f8 <+12>: cbz x0, 0x102080700 ; <+788> (lldb) br list Current breakpoints: 1: name = 'SSL_new', locations = 3, resolved = 3, hit count = 1 1.1: where = libboringssl.dylib`SSL_new, address = 0x0000000193f1b160, resolved, hit count = 0 1.2: where = libssl.48.dylib`SSL_new, address = 0x000000026907f64c, resolved, hit count = 0 1.3: where = libssl.3.dylib`SSL_new, address = 0x00000001020803ec, resolved, hit count = 1 (lldb) We are out of ideas on how to debug this.
23
0
837
Oct ’24
How to Reply to a Message Received by Multicast Receiver and Extract Connection for Communication
Hello everyone, I’m currently working on a Swift project using the Network framework to create a multicast-based communication system. Specifically, I’m implementing both a multicast receiver and a sender that join the same multicast group for communication. However, I’ve run into some challenges with the connection management, replying to multicast messages, and handling state updates for both connections and connection groups. Below is a breakdown of my setup and the specific issues I’ve encountered. I have two main parts in the implementation: the multicast receiver and the multicast sender. The goal is for the receiver to join the multicast group, receive messages from the sender, and send a reply back to the sender using a direct connection. Multicast Receiver Code: import Network import Foundation func setupMulticastGroup() -> NWConnectionGroup? { let multicastEndpoint1 = NWEndpoint.hostPort(host: NWEndpoint.Host("224.0.0.1"), port: NWEndpoint.Port(rawValue: 45000)!) let multicastParameters = NWParameters.udp multicastParameters.multipathServiceType = .aggregate do { let multicastGroup = try NWMulticastGroup(for: [multicastEndpoint1], from: nil, disableUnicast: false) let multicastConnections = NWConnectionGroup(with: multicastGroup, using: multicastParameters) multicastConnections.stateUpdateHandler = InternalConnectionStateUpdateHandler multicastConnections.setReceiveHandler(maximumMessageSize: 16384, rejectOversizedMessages: false, handler: receiveHandler) multicastConnections.newConnectionHandler = newConnectionHandler multicastConnections.start(queue: .global()) return multicastConnections } catch { return nil } } func receiveHandler(message: NWConnectionGroup.Message, content: Data?, isComplete: Bool) { print("Received message from \(String(describing: message.remoteEndpoint))") if let content = content, let messageString = String(data: content, encoding: .utf8) { print("Received Message: \(messageString)") } let remoteEndpoint = message.remoteEndpoint message.reply(content: "Multicast group on 144 machine ACK from recv handler".data(using: .utf8)) if let connection = multicastConnections?.extract(connectionTo: remoteEndpoint) { connection.stateUpdateHandler = InternalConnectionRecvStateUpdateHandler connection.start(queue: .global()) connection.send(content: "Multicast group on 144 machine ACK from recv handler".data(using: .utf8), completion: NWConnection.SendCompletion.contentProcessed({ error in print("Error code: \(error?.errorCode ?? 0)") print("Ack sent to \(connection.endpoint)") })) } } func newConnectionHandler(connection: NWConnection) { connection.start(queue: .global()) connection.send(content: "Multicast group on 144 machine ACK".data(using: .utf8), completion: NWConnection.SendCompletion.contentProcessed({ error in print("Error code: \(error?.errorCode ?? 0)") print("Ack sent to \(connection.endpoint)") })) } func InternalConnectionRecvStateUpdateHandler(_ pState: NWConnection.State) { switch pState { case .setup: NSLog("The connection has been initialized but not started") case .preparing: NSLog("The connection is preparing") case .waiting(let error): NSLog("The connection is waiting for a network path change. Error: \(error)") case .ready: NSLog("The connection is established and ready to send and receive data.") case .failed(let error): NSLog("The connection has disconnected or encountered an error. Error: \(error)") case .cancelled: NSLog("The connection has been canceled.") default: NSLog("Unknown NWConnection.State.") } } func InternalConnectionStateUpdateHandler(_ pState: NWConnectionGroup.State) { switch pState { case .setup: NSLog("The connection has been initialized but not started") case .waiting(let error): NSLog("The connection is waiting for a network path change. Error: \(error)") case .ready: NSLog("The connection is established and ready to send and receive data.") case .failed(let error): NSLog("The connection has disconnected or encountered an error. Error: \(error)") case .cancelled: NSLog("The connection has been canceled.") default: NSLog("Unknown NWConnection.State.") } } let multicastConnections = setupMulticastGroup() RunLoop.main.run() Multicast Sender Code: import Foundation import Network func setupConnection() -> NWConnection { let params = NWParameters.udp params.allowLocalEndpointReuse = true return NWConnection(to: NWEndpoint.hostPort(host: NWEndpoint.Host("224.0.0.1"), port: NWEndpoint.Port(rawValue: 45000)!), using: params) } func sendData(using connection: NWConnection, data: Data) { connection.send(content: data, completion: .contentProcessed { nwError in if let error = nwError { print("Failed to send message with error: \(error)") } else { print("Message sent successfully") } }) } func setupReceiveHandler(for connection: NWConnection) { connection.receive(minimumIncompleteLength: 1, maximumLength: 65000) { content, contentContext, isComplete, error in print("Received data:") print(content as Any) print(contentContext as Any) print(error as Any) setupReceiveHandler(for: connection) } } let connectionSender = setupConnection() connectionSender.stateUpdateHandler = internalConnectionStateUpdateHandler connectionSender.start(queue: .global()) let sendingData = "Hello, this is a multicast message from the process on mac machine 144".data(using: .utf8)! sendData(using: connectionSender, data: sendingData) setupReceiveHandler(for: connectionSender) RunLoop.main.run() Issues Encountered: Error Code 0 Even When Connection Refused: On the receiver side, I encountered this log: nw_socket_get_input_frames [C1.1.1:1] recvmsg(fd 8, 9216 bytes) [61: Connection refused] Error code: 0 Ack sent to 10.20.16.144:62707 Questions: how do I reply to the message if above usage pattern is wrong? how do I get a NWConnection from the received message to create a separate connection for communication with the sender. Any insights or suggestions on resolving these issues or improving my multicast communication setup would be greatly appreciated. Thanks :)
4
0
399
Oct ’24
NWConnection and "Network is Down" error connecting to ip address and port
I have a pretty straightforward code to connect to a given ip address and port using NWConnection. On the first attempt to connect to the Local Network I see the "Local Network Privacy" dialog and sometimes if I press "Don't Allow" on that dialog everything starts to fail. No matter I do I keep receiving the following error: POSIXErrorCode(rawValue: 50): Network is down Obviously going to settings and allowing local network access to the app doesn't fix the issue. Neither deleting the app and installing it again. The only workaround I found is to restart my device which is unacceptable for a user. My code is really simple, I tried a lot of different approaches to connect but neither approach worked. I am on iOS 18. Is it a known bug? could be possible a bug on my code? Any idea would be really appreciated, thanks!
13
2
708
Nov ’24
How can I capture packets while using Wi-Fi or a hub?
I encountered a problem during the development process. I want to enable the rvi0 capture interface using the rvictl command in the terminal while debugging over Wi-Fi in Xcode, but there is no response. Then I tried a different method by connecting the iPhone to a hub. At this point, I can see the device normally in both Xcode and the console, but I still cannot use the rvictl command. How can I capture packets while using Wi-Fi or a hub?
7
0
206
Dec ’24
responseHandler of sendProviderMessage of NETunnelProviderSession is being called implicitly/prematurely
Hi, For one our requirement sendProviderMessage is been used to send some event/message from app to system extension, In my requirement, responseHandler in system extension would get explicitly called approximately after 1 min due to some async download file task. But observing some strange behavior that responseHandler is getting called implicitly after ~20-30 seconds even before the code hit the place where its called explicitly. And that is the only place I'm calling responseHandler. Can somebody please help about this strange behavior, Is there any implicit timeout interval associated with the responseHandler. Thanks &amp;amp; Regards, Preethi
1
0
229
4w
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
134
4w
Clarification on .v6 Listener Accepting Both IPv4 and IPv6 Traffic vs NWListener with .any
Hello everyone, I have a question regarding the behavior of network listeners in my application. Here's the scenario I'm seeing: When I open a .v6 listener, it accepts both IPv4 and IPv6 traffic. However, when I run the netstat -tln command, the socket is shown as udp6. When I open a NWListener with the IP version set to .any, I receive both IPv4 and IPv6 traffic on the listener. In this case, running netstat -tln shows a udp46 socket. My understanding is that if I create a socket with .v6, it should only accept IPv6 connections, not both IPv4 and IPv6. However, the .v6 listener appears to be accepting both types of traffic, which is causing some confusion. Additionally, I am seeking to understand the difference between a udp6 socket and a udp46 socket, and also the difference between sockets created using .v6 and .any. What exactly does udp46 represent, and how is it different from udp6 in terms of accepting traffic? Is this expected behavior, or is there something I am missing in how the listeners are set up? Looking forward to hearing your insights!
1
0
162
4w
Disabling Fragmented Packets on NWConnection - What Is Expected from disableFragmentation?
Hello everyone, We have a use case where we need to disable the sending and receiving of fragmented packets on the network while using NWConnection. However, even after setting the disableFragmentation flag to true, the connection still sends fragmented packets.We’ve tried setting the flag as follows, but the packets are still being fragmented: var connection : NWConnection var udp_options : NWProtocolUDP.Optionsudp_options = NWProtocolUDP.Options() var connection_parameters = NWParameters(dtls: nil, udp: udp_options) let ip_options = connection_parameters.defaultProtocolStack.internetProtocol! as! NWProtocolIP.Options ip_options.disableFragmentation = true connection = NWConnection (host: "XX.XX.XX.***", port: NWEndpoint.Port(25000), using: connection_parameters) The issue we are encountering is that even though we’ve set disableFragmentation to true on the sender, the receiver still receives fragmented UDP packets. This can be observed using Wireshark, where we are sending a 10k byte data from the sender and receiving the fragmented datagram packets on the receiver end while both the devices are on the same WiFi network. Additionally, Wireshark shows that the packet has the "DF" bit set to '0', indicating that fragmentation is allowed. What is exactly expected from the disableFragmentation flag? Are we misunderstanding how this flag works? Or is there something else we should be doing to ensure that fragmentation is completely disabled? Looking forward to your insights!
1
0
152
4w
After iOS 18,can not connect to Lot devices hotpot
when my iPhone15 pro max upgrade to iOS18.1.1,it can not connect to hotPot of my lot device(os android5.1) any more and my iPhone12(iOS 18.1.1) has no issues. Both the 15 pro max and the iPhone12 works well with another device (OS android 10.0). had tried: 1.Forget Network (and re-add your desired Wifi network), 2.Reset Network Settings (under Settings/General/Transfer or Reset iPhone) 3.Turn Airplane Mode On then Off after a few seconds 4.Restart the iPhone. 5.Rest all setting 6.Disable VPN 7.close the the settings from rotating my WiFi address Did anyone have similar issues?
1
0
153
4w
Notifications on iOS sourced from a machine on an offline local network
We have a device which is an appliance and we are developing a control interface app for macOS and iOS/iPadOS. How can we set up our iOS application to grab information from a local network device while it is in the background in order to show notifications? Communication between the Apple device and our device is via local networking and the device is designed to be used on networks without internet connections. On networks with internet connections we could forward events from the device, via a server and APNS push notifications, but that isn't valid here. Events occur on our device and are forwarded to clients, who are subscribed to Server-Sent Events. On macOS this works well and the application can receive updates and show Notification Center notifications fine. On iOS we are using a BGAppRefreshTaskRequest with time interval set to 1 minute, but it appears that we get scheduled only every few hours. This isn't very useful as notifications just arrive in batches rather than in a timely manner. All normal networking is closed when the app goes into the background, so we cannot keep the SSE request open. Another idea which we haven't tried yet: Creating a new endpoint on the device which keeps the connection open until a notification arrives, then using background URLSession to poll on that endpoint. Would that work? It seems like a mis-use of the API perhaps?
9
0
294
Dec ’24
Force socket() level UDP sockets to use IGMP v2 and not adaptive to v3
I'm working with an app that was developed with the CocoaAsyncSocket library, which uses <sys/socket.h> style socket programming. We have a customer where certain features are not working if iOS "adapts" to v3 IGMP but seems to work if v2 IGMP is used. I can't say I understand all the low level aspects and am trying to inform myself. I've been searching online to find out about socket and IGMP but don't see anything coming up. Is there a way to force iOS to use IGMP v2 for broadcast? Our company also makes a hardware communicator and their code forces v2 and we've been asked to see if we can do the same. Thanks for any leads on where to go to inform myself. more or code snippets on how to do this.
2
0
206
Dec ’24