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

Alternatives to nettop for Monitoring Process Network Usage on macOS
Hi everyone, I am developing an application for macOS and need to monitor the network usage (bytes sent and received) of specific processes. Previously, I used the nettop command to achieve this, but I found that it leads to high CPU usage, often reaching 95%. I'm looking for alternative methods to obtain the network usage information of processes. This could be through a different command or an available macOS API. Any suggestions or guidance on more efficient ways to gather this data would be greatly appreciated. Thank you!
1
0
384
Jun ’24
Network framework and background tasks
Hi team, I'm working on an MQTT client for Apple platforms (macOS, iOS, and possibly tvOS and watchOS). I would like the client to listen to messages even when the application is in the background. I would appreciate any suggestions on the best approach to achieve this. Based on iOS Background Execution Limits, it seems that my best bet is to use a long-running background process with BGProcessingTaskRequest while setting up the connection. Does that sound like the right approach? Is there any limits for the bg tasks? I currently have a working BSD socket. I'm not sure if it is necessary to switch to the Network Framework to have the background task working, but I'm open to switching if it's necessary. If the approach works, does that mean I could built a http client to process large upload/download tasks without using NSURLSession? As I'm working on a cross platform project, it would be benefit if I dont need a separate http client implementation for Apple. Any insights on this topic would be greatly appreciated. Additionally, it's off topic, but the link to "WWDC 2020 Session 10063 Background Execution Demystified" (https://developer.apple.com/videos/play/wwdc2020/10063/) is broken. Is there a way to access the content there? Thanks in advance for your help and insights!
9
0
1.1k
Jun ’24
iOS App udp and local network permission
Recently, my application was having trouble sending udp messages after it was reinstalled. The cause of the problem was initially that I did not grant local network permissions when I reinstalled, I was aware of the problem, so udp worked fine after I granted permissions. However, the next time I repeat the previous operation, I also do not grant local network permissions, and then turn it back on in the Settings, and udp does not work properly (no messages can be sent, the system version and code have not changed). Fortunately, udp worked after rebooting the phone, and more importantly, I was able to repeat the problem many times. So I want to know if the process between when I re-uninstall the app and deny local network permissions, and when I turn it back on in Settings, is that permissions have been granted normally, and not fake, and not required a reboot to reset something for udp to take effect. I'm not sure if it's the system, or if it's a similar situation as described here, hopefully that will help me find out
5
2
1.3k
Jun ’24
Does macOS/Sequoia require a new entitlement to send multicast packets?
Hi all, My co-worker today noticed that on his Mac running a beta of Sequoia, the IPv6 multicast functionality of our application was no longer working. This same executable works fine under Sonoma and earlier versions of MacOS, and has worked fine for a number of years. Under Sequoia, however, calls to sendto() a packet to an IPv6-link-local-multicast address (e.g. ff12::bead:cede:deed:feed, preceeded by a call to setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, ...) to specify the appropriate network interface index) return -1 and set errno to EHOSTUNREACH aka "No route to host". The interesting thing about it is, this problem only occurs if we launch our app by double-clicking on its icon; if we instead run the app from Terminal (e.g. by entering ./MyApp.app/Contents/MacOS/MyApp), the multicast functionality works as expected. Our app is signed and notarized in all the usual expected ways. My question is, is this "just" a networking regression in the Sequoia beta, or is there some new requirement in macOS/Sequoia for IPv6-link-local-multicast-using apps to have a multicast entitlement (a la iOS) or something?
7
0
2.7k
Jun ’24
How to reset Local Network Privacy settings?
On macOS 15, if a program installed in /Applications is allowed to connect to a PostgreSQL server on another machine on the local network, a program launched in debug mode from Xcode is not allowed to connect to the local network, and no prompt appears. Although it is possible to turn off registered programs in Local Network Privacy in Beta 2, permissions for programs launched from Xcode cannot be obtained at all. Does anyone know how to solve this problem?
3
1
2.1k
Jun ’24
iOS VPN: Loss of Internet Connectivity on iOS Device post Packet Tunnel Crashes
Title: Loss of Internet Connectivity on iOS Device When Packet Tunnel Crashes Feedback ticket: https://feedbackassistant.apple.com/feedback/14162605 Product: iPhone 12 Version: iOS - 17.5.1 Configuration: NETunnelProviderManager Configuration Description: We are developing an iOS VPN client and have configured our packet tunnel provider according to Apple's guidelines. The configuration is as follows: includeAllNetworks = YES excludeLocalNetworks = NO enforceRoutes = NO This setup works as expected when the VPN successfully connects. However, we encounter a blocker issue where the device loses internet connectivity if the packet tunnel crashes. Steps to Reproduce: Configure the NETunnelProviderManager with the above settings. Connect the VPN, which successfully establishes a connection. Verify that resources are accessible and internet connectivity is functional. Packet tunnel to crash unexpectedly.Observe that the NE process (Packet Tunnel) restarts automatically, as expected and attempts to reconnect the VPN; however, the device now lacks internet connectivity, preventing VPN reconnection. Try accessing resources using Safari or any other internet-dependent app, resulting in an error indicating the device is not connected to the internet. Actual Results: The device loses internet connectivity after the packet tunnel crashes and fails to regain it automatically, preventing the VPN from reconnecting. Expected Results: The device should maintain internet connectivity or recover connectivity to allow the VPN to reconnect successfully after the packet tunnel process restarts. Workaround - iPhone device needs a restart to regain internet connectivity .
2
0
538
Jul ’24
Network Connection on watchOS App
I am developing a watchOS-only app, and whenever I attempt to make a network request, it always fails and throws the following error: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." I noticed that when I turn off Wi-Fi and Bluetooth in the settings of the iPhone paired with the Apple Watch (thus disconnecting the Apple Watch from the iPhone), my app can successfully connect to the network. Additionally, when the app contains both an iOS app and a watchOS app, after granting network permissions on the iOS app, the watchOS app can access the network normally when connected to the iPhone. When opening some system apps on the Apple Watch (such as the "Workout" app), the app will display a network permission request similar to that on iOS, but this request does not automatically pop up when my watchOS app attempts to access the network. Is there a way to request network permissions in a watchOS-only app so that it can access the network while connected to the iPhone?
3
0
1k
Jul ’24
Crash in connection loader from CFNetwork with stack traces referring to internal Apple SDKs
We found there is a significant crash reports (most of them are from iOS 17, the rest are iOS 16 and 15) comes from network loader from CFNetwork. Apparently it seems there are two types of crashes if we checked from the stack trace, the one we found from both Xcode organizer and 3rd party crash reporter is referring to URLConnectionLoader::loadWithWhatToDo and the other one from our 3rd party crash reporter (didn’t found the report from Xcode organizer) referring to _CFURLResponseCreateFromArchiveList (this one only happened on iOS 17.5 and later devices). It seems that they are both kinda similar which might point to the same root cause. From what I’ve seen, we never touch the lower level API directly, we usually use the URLSession to manage our API request. The crashed stack trace also didn’t give any indication about which of our app code that triggered the crash, it only shows calls to Apple’s internal SDKs so we are unsure how to approach this issue meanwhile the crash event already reached 800+ in the last 30 days. Unfortunately, we cannot reproduce the issue as the stack trace itself seems unclear to us. I have submitted a report through feedback assistant with number: FB14679252. Would appreciate if anyone can give any advice on what we can do to avoid this in the future and probably any hint on why it could happened. Hereby I attached the crash reports that we found each from Xcode crash report and our 3rd party crash reporter (the report said it crashed on com.apple.CFNetwork.LoaderQ) so you could get a glimpse of the similarity. Xcode crash report xcode crash report.crash 3rd party crash report 3rd party crash report.txt
5
1
1.5k
Aug ’24
Unable to recover after URLSession encounters the SSL error -9816
For years our iOS apps have experienced a networking problem, which blocks them connecting to our servers via their API endpoint domains. How can we recover after the scenario described below? Using 3rd party error logging solutions, which have different endpoint domains, we can record the error: NSUnderlyingError": Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9816, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9816, _NSURLErrorNWPathKey=satisfied (Path is satisfied), viable, interface: pdp_ip0[lte], ipv4, dns, expensive, uses cell}, "_NSURLErrorFailingURLSessionTaskErrorKey": LocalDataTask <DEDBFA4D-810D-4438-A6A0-95E3B9668B9E>.<308>, "_kCFStreamErrorDomainKey": 3, "_NSURLErrorRelatedURLSessionTaskErrorKey": <__NSSingleObjectArrayI 0x301f82e60>( LocalDataTask <DEDBFA4D-810D-4438-A6A0-95E3B9668B9E>.<308> ) "NSLocalizedDescription": An SSL error has occurred and a secure connection to the server cannot be made., "NSLocalizedRecoverySuggestion": Would you like to connect to the server anyway? -9816 is the "server closed session with no notification" error based on comments in CoreFoundation source files. Subsequent API endpoint calls to the same domain return the same error. The SSL error occurs most prevalently after a server outage. However, despite our best efforts, we have been unable to replicate triggering the problem for development purposes via experiments with our server. When the error occurs the users report that: Fully closing (i.e. not just sending to background) and reopening the app does NOT clear connectivity to our server being blocked. Problem seems more prevalent when using mobile/cell data. Switching from mobile/cell data to WIFI resolves the connection problem and then switching back to mobile/cell data shows the problem again. So the underlying problem is not cleared. All other apps on the same device and mobile/cell data or WIFI connection, like Safari, have no problems connecting to the Internet. Deleting and reinstalling, or updating (when an update is available) resolves the problem. Or after waiting a few days the problem seems to resolve itself. The last two point above suggest that something is persisted/cached in the app preventing it from connecting properly with subsequent network attempts. Notes: We have one shared instance of the URLSession in the app for its networking because we are aware of the perils of multiple URLSession instances. We recently added conditions to call the URLSession await reset() method when detecting the SLL errors before repeating the request. It is debatable whether this reduces the problem as we still see logged cases with the subsequent requests hitting the same -9816 error. URLSession configuration: let config = URLSessionConfiguration.default config.timeoutIntervalForResource = 22 config.timeoutIntervalForRequest = 20 config.requestCachePolicy = .reloadIgnoringLocalCacheData config.urlCache = nil
7
3
1.4k
Aug ’24
Allow "App" to find the devices on local network?
Hi, On macOS 15 beta 7, we get a network popup while launching application, "Allow "App" to find the devices on local network?" This popup we are not seeing in older versions of macOS. We also see a a new option in "System Settings->Privacy & Security->Local Network". Is there way to add the application entry in "Local Network" through a command so that we can suppress this popup on launching the applications? Regards Prema Kumar
9
0
12k
Aug ’24
Simulator unable to connect to localhost, working fine when opened directly in laptop
I am trying to connect to localhost:8081 from simulator, but it is unable to connect with following logs: info 12:07:49.167248+0530 com.apple.WebKit.Networking nw_resolver_host_resolve_callback [C8.1] flags=0x40000003 ifindex=0 error=NoSuchRecord(-65554) hostname=localhost. addr=IN6ADDR_ANY ttl=60 info 12:07:49.167310+0530 com.apple.WebKit.Networking nw_resolver_host_resolve_callback [C8.1] flags=0x40000002 ifindex=0 error=NoSuchRecord(-65554) hostname=localhost. addr=INADDR_ANY ttl=108002 Macos 14.6.1 iOS simulator version 17.5 Som observations localhost:8081 does not load on simulator but 0.0.0.0:8081 loads fine, also 127.0.0.0:8081 loads fine on simulator. My laptop is a managed device with network filter Switching network sometimes fixes the issue. Restarting laptop sometimes fixes the issue. localhost:8081 opens find on laptop, but not on simulator. Contents of my laptop's /etc/hosts: ## # Host Database # # localhost is used to configure the loopback interface # when the system is booting. Do not change this entry. ## 127.0.0.1 localhost 255.255.255.255 broadcasthost ::1 localhost
9
0
2.4k
Aug ’24
How can we get the BSSID value for a wifi network without sudo
How can we get the BSSID value for a wifi network without sudo we have tried with different options but they dont seem to work.It seems they have been deprecated. /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport en1 --getinfo | grep BSSID | awk -F ': ' '{print $2}' ioreg -l -n AWDLPeerManager | perl -lne 'print $1 if $_ =~ /IO80211BSSID.&lt;(.)&gt;/;' | fold -w2 | paste -sd: -
1
1
1k
Aug ’24
How to add (another) default route to link layer address?
Greetings, I am trying to mimic what the official WireGuard client (available on AppStore, source code is publicly available) does regarding the routing tables. The client uses NetworkExtension framework. When a VPN connection is established with all traffic routed through WireGuard (AllowedIPs = 0.0.0.0/0), the routing table is amend with something like this: Destination Gateway RT_IFA Flags Refs Use Mtu Netif Expire default link#36 10.10.10.2 UCSg 114 0 1420 utun7 10.10.10.2 10.10.10.2 10.10.10.2 UH 0 10 1420 utun7 224.0.0/4 link#36 10.10.10.2 UmCS 0 0 1420 utun7 255.255.255.255/32 link#36 10.10.10.2 UCS 0 0 1420 utun7 Please note that another default route exists to the working Ethernet interface, but I have not mentioned it above. I would like to do something similar for wireguard-go (open source WireGuard implementation written in Go), in particular start it, assign an IP address, then add the routes. sudo env LOG_LEVEL=debug wireguard-go -f utun sudo ifconfig utun5 10.10.10.2 10.10.10.2 netmask 255.255.255.255 Here is the code fragment written in C which suppose to add default route (0.0.0.0/0) to the link layer address: void add_link_route() { struct { struct rt_msghdr hdr; struct sockaddr_in dest; struct sockaddr_dl gateway; struct sockaddr_in netmask; } rt; memset(&amp;rt, 0, sizeof(rt)); int sockfd = socket(PF_ROUTE, SOCK_RAW, 0); if (sockfd == -1) { perror("socket"); return; } unsigned int if_index = if_nametoindex("utun5"); rt.hdr.rtm_msglen = sizeof(rt); rt.hdr.rtm_version = RTM_VERSION; rt.hdr.rtm_type = RTM_ADD; rt.hdr.rtm_index = if_index; rt.hdr.rtm_flags = RTF_UP | RTF_STATIC | RTF_CLONING; rt.hdr.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK; rt.hdr.rtm_seq = 1; rt.hdr.rtm_pid = getpid(); rt.dest.sin_len = sizeof(struct sockaddr_in); rt.dest.sin_family = AF_INET; rt.dest.sin_addr.s_addr = INADDR_NONE; rt.gateway.sdl_len = sizeof(struct sockaddr_dl); rt.gateway.sdl_family = AF_LINK; rt.gateway.sdl_index = if_index; rt.gateway.sdl_type = IFT_PPP; rt.netmask.sin_len = sizeof(struct sockaddr_in); rt.netmask.sin_family = AF_INET; rt.netmask.sin_addr.s_addr = INADDR_NONE; if (write(sockfd, &amp;rt, sizeof(rt)) == -1) { perror("write"); } close(sockfd); } But, when executed, write() returns EEXIST (File exists) error, meaning, the default route cannot be overwritten (because another default route exists which points to the existing Ethernet interface). At this point I have no idea how the routes could be created successfully inside NetworkExtension, and I would like to do the same. For comparison, there is another case when all traffice is not routed through the VPN. Then, the routes are created like this: Destination Gateway RT_IFA Flags Refs Use Mtu Netif Expire default link#36 10.10.10.2 UCSIg 0 0 1420 utun7 10.10.10.2 10.10.10.2 10.10.10.2 UH 0 0 1420 utun7 224.0.0/4 link#36 10.10.10.2 UmCSI 0 0 1420 utun7 255.255.255.255/32 link#36 10.10.10.2 UCSI 0 0 1420 utun7 The difference is that now the scope is bound to the network interface. And in such case, my C code succeeds, providing I add RTF_IFSCOPE flag to rtm_flags. I would appreciate if someone helped me with this problem.
1
0
441
Sep ’24
Cannot enable Network Extensions - Objective-C
So I wanted to get my hands dirty with objective-c so I decided to create a project to list all outbound traffic, after digging a little I found that I could use the Network Extension API. I created a simple command line project with xcode and tried to load this extension but for some reason I can't get it to work. I don't have a developer license yet and I'm not sure if it has anything to do with the problem I'm facing. This is just some test code so there are 2 free functions, one for loading the system extension and another for checking its status: // activates the extension? BOOL toggleNetworkExtension(NSUInteger action) { BOOL toggled = NO; __block BOOL wasError = NO; __block NEFilterProviderConfiguration* config = nil; dispatch_semaphore_t semaphore = 0; semaphore = dispatch_semaphore_create(0); NSLog(@"toggling the network extension"); [NEFilterManager.sharedManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if(nil != error) { wasError = YES; NSLog(@"loadFromPreferencesWithCompletionHandler error"); } dispatch_semaphore_signal(semaphore); }]; NSLog(@"waiting for the network extension configuration..."); if(YES == wasError) goto fail; NSLog(@"loaded current filter configuration for the network extension"); if(1 == action) { NSLog(@"activating network extension...") ; if(nil == NEFilterManager.sharedManager.providerConfiguration) { config = [[NEFilterProviderConfiguration alloc] init]; config.filterPackets = NO; config.filterSockets = YES; NEFilterManager.sharedManager.providerConfiguration = config; } NEFilterManager.sharedManager.enabled = YES; } else { NSLog(@"deactivating the network extension..."); NEFilterManager.sharedManager.enabled = NO; } { [NEFilterManager.sharedManager saveToPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if(nil != error) { wasError = YES; NSLog(@"saveToPreferencesWithCompletionHandler error!"); } dispatch_semaphore_signal(semaphore); }]; } NSLog(@"waiting for network extension configuration to save..."); if(YES == wasError) goto fail; NSLog(@"saved current filter configuration for the network extension"); toggled = YES; fail: return toggled; } Then there's this function to check if the extension is enabled which for some reason always returns false. BOOL isNetworkExtensionEnabled(void) { __block BOOL isEnabled = NO; dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); [NEFilterManager.sharedManager loadFromPreferencesWithCompletionHandler:^(NSError * _Nullable error) { if (error != nil) { NSLog(@"Error with loadFromPreferencesWithCompletionHandler"); } else { isEnabled = NEFilterManager.sharedManager.enabled; } dispatch_semaphore_signal(semaphore); }]; return isEnabled; } Is something wrong is this code or is this related to entitlements or the developer license? As a side note I have already disabled SIP not sure if it matters in this case. Thanks in advance.
1
0
684
Sep ’24
Using MPSession sendResource Progress in a SwiftUI ProgressView causes crash
When transferring files in a Multipeer Session, using the Progress instances (returned by either sendResource in the sender or the delegate method session(didStartReceiving:) on the receiver) in a SwiftUI ProgressView will eventually cause a crash (EXC_BAD_ACCESS in swift_retain on com.apple.MCSession.syncQueue) I have created a small sample project that demonstrates the problem. It can be found at: https://github.com/eidria/Multipeer-Progress-Demo.git. A screen shot of the stack trace from a crash (crash.jpg) is in the “Images” folder. STEPS TO REPRODUCE Run the sample on two different hosts connected to the same network (project contains both iOS & macOS targets, bug manifests in any combination). When the second instance comes up, they will automatically find and connect to each other. When the “Send Files” button is enabled, clicking it will cause the sender to repeatedly send the file “Image.HEIC” from the “Images” folder to the receiver, which deletes it upon receipt of a successful transfer (i.e. delegate call back is called with a nil error). Subsequent transfers are triggered when the sender receives notice that the prior send completed successfully. Eventually, after some (usually small) number of files have been transferred, either the sender or receiver will crash in the middle of a transfer, with EXC_BAD_ACCESS in swift_retain on com.apple.MCSession.syncQueue. Commenting out the ProgressView in the file FileTransferView.swift will allow the apps to run in perpetuity.
2
0
727
Sep ’24
Wifi Monitor Mode
Howdy everyone, I'm researching for a potential product so I can't give too many details. To be brief, I need to put an iPhone or iPad into Wifi Monitor mode. I plan on creating an app to control this for users to utilize. I can't find material on this topic in the Xcode Docs, or if the iPhone/iPad even supports Wifi Monitor mode. Does anyone know if it's even possible?
0
0
470
Sep ’24
"_nw_activity_is_equal" Crash When Initiating NSURLSession Task on App Startup
Dear Apple Developer Team, We have encountered a recurring issue where our application crashes when initiating an NSURLSession task immediately after startup. The crash appears to be sporadic, but we have observed a few instances where it consistently happens right after launching the app and starting an NSURLSession task. The crash stack trace is as follows: _objc_retain_x20 _nw_activity_is_equal ___nw_activity_activate_block_invoke nw_synchronize<nw::unfair_mutex, void () block_pointer __strong>(nw::unfair_mutex*, void (&&)() block_pointer __strong) _nw_activity_activate sub_1893e49b0 From the stack trace, it appears that the crash is related to network activity synchronization (nw_synchronize) and activity activation (_nw_activity_activate). This issue could potentially be linked to some internal network state management or threading issues within the networking stack. Steps to Reproduce: 1. Launch the app. 2. Immediately initiate an NSURLSession task. Most important, it seems be happen after iOS17. Hoping your kind answer!
1
0
270
Sep ’24
Network Local Privacy pop-up on macos Sequoia
Starting from macOS 15 (macOS Sequoia), a new pop-up is triggered: “Local Network Privacy.” We have some questions regarding this new pop-up on MacOS: Running the following simple code: cups_dest_t *dests; int num_dests = cupsGetDests(&amp;dests); triggers the “Local Network Privacy” pop-up. Question: Is this intended behavior? Even if the user presses the “Deny” button, printers can still be iterated, and it is possible to set options for the printer. Is this intended behavior? If so, which actions related to the CUPS library will be denied when the user presses the “Deny” button? Question: Should this pop-up appear for daemons/launchd processes? We found similar questions on some forums, but the answers are unclear. It seems that the pop-up should not appear for launch daemons. We tested the mentioned code with CUPS, and the pop-up was triggered. Is this a bug? If so, will it be resolved before the new macOS version is released? Question: There is somewhere documented all the scenarios in which this pop-up may appear is challenging? Regarding automatically allowing or disallowing the pop-up: We found the following response: “There is no way to automatically allow or disallow the local network privacy prompt. If it shows up in your app, you will need to analyze your code to better understand how the prompt is being triggered. If the prompt is triggered by a library you do not control, you will need to either remove the library or inquire further with the library vendor.” Question: How can we ensure that a launchd daemon will work as expected if the user presses the “Deny” button? Is there any way to detect if the user pressed “Deny”?
8
0
1.9k
Sep ’24
Error 0x6f - Invalid or missing Program/ProgramArguments
We have an iOS app which includes a packet tunnel provider network extension. We have noticed on rare occasions that the VPN fails to start when we try to start the VPN from the app after installing it. However, rebooting the device or reinstalling the app fixes the issue. When creating the sysdiagnose file, we found some strange messages, a snippet is given below: 2024-09-10 13:40:20.291430 +0100 launchd Could not find and/or execute program specified by service: 2: No such file or directory: /private/var/containers/Bundle/Application/2FA92604-C67D-490D-8E8E-00F8D6FBF990/Sample.app/PlugIns/Tunnel.appex/Tunnel error 2024-09-10 13:40:20.291456 +0100 launchd Service could not initialize: access(/private/var/containers/Bundle/Application/2FA92604-C67D-490D-8E8E-00F8D6FBF990/Sample.app/PlugIns/Tunnel.appex/Tunnel, X_OK) failed with errno 2 - No such file or directory, error 0x6f - Invalid or missing Program/ProgramArguments We encountered this before several months ago on iOS 17.4 and reported it when the issue occurred, but this issue continues to be present in the iOS 18 release candidate. Is there any solution for this issue? Feedback ID: FB13714761
3
1
567
Sep ’24