Post not yet marked as solved
I'm working on an app that does peer-to-peer communication between Apple devices. As far as I understand, the Network framework is a good choice for this. I have something that works, but I'm curious about the details of how this works and if I might somehow optimize this.
My current understanding is that the best connection I can get between two devices is over AWDL. Is this true? If so, does Network use this? Can I ask it to use it preferentially? What kind of bandwidth and latency should I expect out of this, and are there any drawbacks to using it like power usage or transport limitations?
If both devices are on the same LAN, I assume they can also talk to each other over Wi-Fi (or a wired connection if both are plugged in, I guess). If I use Bonjour service discovery, is this what I will be getting? What does Network do if the LAN network does not perform well? Will it swap the underlying connection if it figures out there is something better?
I am not tied to any particular API or transport protocol, so any input on tradeoffs between ease of implementation/performance/reliability/whatever would be welcome :)
Post not yet marked as solved
I have a sample iOS app in Xcode that I run in the iOS 17.5 Simulator. It creates a WKWebView and configures a proxy via the ProxyConfiguration API, it works as expected unless the proxy tries to establish mTLS. It seems there is no way to handle the client certificate request when using a proxy. If I navigate to a page that requests mTLS without a proxy configured, it works as expected. Here is a minimal repro:
#import "ViewController.h"
#import <WebKit/WebKit.h>
@import Foundation;
@import WebKit;
@interface ViewController () <WKNavigationDelegate>
@property (nonatomic,strong) WKWebView* webView;
@property (nonatomic, strong) WKWebViewConfiguration * webConfig;
@end
@implementation ViewController
- (void)loadView {
[super loadView];
nw_protocol_options_t tls_options = nw_tls_create_options();
sec_protocol_options_t sec_options = nw_tls_copy_sec_protocol_options(tls_options);
sec_protocol_options_set_challenge_block(
sec_options,
^(sec_protocol_metadata_t metadata, sec_protocol_challenge_complete_t challenge_complete) {
NSLog(@"Inside of challenge block");
challenge_complete(nil);
},
dispatch_get_main_queue());
nw_endpoint_t proxy_endpoint =
nw_endpoint_create_host(GetHost(), GetPort());
nw_relay_hop_t relay =
nw_relay_hop_create(nil, proxy_endpoint, tls_options);
nw_proxy_config_t proxy_config =
nw_proxy_config_create_relay(relay, nil);
nw_proxy_config_add_match_domain(proxy_config, "api.ipify.org");
self.webConfig = [[WKWebViewConfiguration alloc] init];
self.webConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
self.webConfig.websiteDataStore.proxyConfigurations = @[ proxy_config ];
self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:self.webConfig];
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%s",__func__);
NSURL* url = [[NSURL alloc] initWithString:@"https://api.ipify.org"];
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
[self.webView loadRequest:request];
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"%s",__func__);
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"%s. Error %@",__func__,error);
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
NSLog(@"%s",__func__);
NSLog(@"protection space: %@", challenge.protectionSpace.authenticationMethod);
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
@end
The logs for this code show:
-[ViewController viewDidLoad]
-[ViewController webView:didStartProvisionalNavigation:]
-[ViewController webView:didFailProvisionalNavigation:withError:]. Error Error Domain=NSURLErrorDomain Code=-1206 "The server “api.ipify.org” requires a client certificate."
If we don't set up the ProxyConfiguration and navigate to a site that requires mTLS, the logs look like this:
-[ViewController viewDidLoad]
-[ViewController webView:didReceiveAuthenticationChallenge:completionHandler:]
protection space: NSURLAuthenticationMethodServerTrust
-[ViewController webView:didReceiveAuthenticationChallenge:completionHandler:]
protection space: NSURLAuthenticationMethodClientCertificate
-[ViewController webView:didStartProvisionalNavigation:]
//...
Eventually the request fails but the key difference is that didReceiveAuthenticationChallenge was invoked. When using the ProxyConfiguration neither that function nor the block we set via sec_protocol_options_set_challenge_block were run.
I also tried to provide the client identity via sec_protocol_options_set_local_identity to no avail, and I've tried configuring these options too but they had no effect
sec_protocol_options_add_tls_application_protocol(sec_options, "h2");
sec_protocol_options_set_max_tls_protocol_version(sec_options, tls_protocol_version_TLSv13);
sec_protocol_options_set_peer_authentication_required(sec_options, true);
Am I missing something? Or is this a bug in the ProxyConfiguration API?
Hello,
I am trying to get network statistics using Swift on macOS. I am attempting to obtain:
total input bytes
total output bytes
total input packets
total output packets
The following code works in the app as far as I can tell so far, but... the for-loop is a hack that I'd like to correct by properly iterating over all the interfaces.
import Foundation
import OSLog
struct NetworkStatisticsData {
var totalInputBytes: UInt64 = 0
var totalOutputBytes: UInt64 = 0
var totalInputPackets: UInt64 = 0
var totalOutputPackets: UInt64 = 0
}
final class NetworkStatistics: Sendable {
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!,
category: "SwiftNetworkInformation")
func getNetworkStatistics() -> NetworkStatisticsData {
var networkStatisticsData = NetworkStatisticsData()
for i in 1..<24 { // <- this for-loop should be iterating over a list of interfaces. NET_RT_IFLIST2 ?
var keys: [Int32] = [ CTL_NET, PF_LINK, NETLINK_GENERIC, IFMIB_IFDATA, Int32(i), IFDATA_GENERAL ]
var mibData: ifmibdata = ifmibdata()
var mibDataSize: size_t = MemoryLayout<ifmibdata>.size
if sysctl(&keys, u_int(keys.count), &mibData, &mibDataSize, nil, 0) < 0 {
logger.error("sysctl error getting mib data: \(String(describing: strerror(errno)))")
}
networkStatisticsData.totalInputPackets += mibData.ifmd_data.ifi_ipackets
networkStatisticsData.totalOutputPackets += mibData.ifmd_data.ifi_opackets
networkStatisticsData.totalInputBytes += mibData.ifmd_data.ifi_ibytes
networkStatisticsData.totalOutputBytes += mibData.ifmd_data.ifi_obytes
}
return networkStatisticsData
}
}
Any thoughts on how to iterate over all of the network interfaces (maybe using NET_RT_IFLIST2)? When I run ifconfig in the terminal, there are 24 interfaces, hence the reason for 24 in the for-loop.
Post not yet marked as solved
As TN3135 clearly explains the limitations apple puts on the low level networking, it doesn’t really give a reason. Presumably the power consumption problem. But as the battery technology continues evolving, it could be exciting that apple might loose the restrictions someday. The watch itself is powerful enough to do a lot of sophisticated works, sure it works best with companion apps on iPhone, but even as a standalone device, we can still provide many advanced user experience with low level networking supports.
wish apple guys can read it and give a consideration.
Post not yet marked as solved
Is it possible to develop two apps in which one should use cellular data only and another one should connect with Wi-Fi socket for data communication?
Post not yet marked as solved
I've been investigating an issue with the SO_OOBINLINE socket option. When that option is disabled, the expectation is that out-of-band data that is sent on the socket will not be available through the use of read() or recv() calls on that socket.
What we have been noticing is that when the socket is bound to a non-loopback address (and the communication is happening over that non-loopback address), then even when SO_OOBINLINE is disabled for the socket, the read()/recv() calls both return the out-of-band data. The issue however isn't reproducible with loopback address, and read()/recv() both correctly exclude the out-of-band data.
This issue is only noticed on macos. I have been able to reproduce on macos M1, following version, but the original report which prompted me to look into this was reported on macos x64. My M1 OS version is:
sw_vers
ProductName: macOS
ProductVersion: 14.3.1
BuildVersion: 23D60
Attached is a reproducer (main.c.txt - rename it to main.c after downloading) that I have been able to develop which reproduces this issue on macos. When you compile and run that:
./a.out
it binds to a non-loopback address by default and you should see the failure log, resembling:
...
ERROR: expected: 1234512345 but received: 12345U12345
To run the same reproducer against loopback address, run it as:
./a.out loopback
and that should succeed (i.e. no out-of-band data) with logs resembling:
...
SUCCESS: completed successfully, expected: 1234512345, received: 1234512345
Is this a bug in the OS? I would have reported this directly through feedback assistant, but my past few open issues (since more than a year) have not even seen an acknowledgement or a reply, so I decided to check here first.
main.c.txt
Post not yet marked as solved
This was mentioned in another thread 4 years ago:
This whole discussion assumes that every network connection requires a socket. This isn’t the case on most Apple platforms, which have a user-space networking stack that you can access via the Network framework [1].
[1] The one exception here is macOS, where Network framework has to run through the kernel in order to support NKEs. This is one of the reasons we’re in the process of phasing out NKE support, starting with their deprecation in the macOS 10.15 SDK.
Is macOS still an unfortunate exception that requires a socket per Network framework's connection?
Initially, my task was to determine which type of connection is being used at the moment: 5G or 4G. And I found "CTTelephonyNetworkInfo().serviceCurrentRadioAccessTechnology" but there is a problem when the device has more than one sim.
My iPhone has two sims, one physical and one electronic.
I need to determine which one is used to access the network. I tried to use "CTTelephonyNetworkInfo().serviceCurrentRadioAccessTechnology" but it is a dictionary [String: String] that only indicates the connection of each of the cards, and it is not possible to find out which one is active from this dictionary. So how can I determine which of the two cards are currently being used to access the Internet?
Post not yet marked as solved
Hello,
I've been encountering some challenges while working with NWConnectionGroup and NWMulticastGroup for multicast operations on iOS. I have a few doubts and issues that I would like to address:
1. NWMulticastGroup Initialization
It seems that when initializing NWMulticastGroup, only one NWEndpoint can be passed, and attempting to pass multiple endpoints results in failure. Can someone confirm if this behavior is correct?
2. Interface Level Control
Upon initializing NWConnectionGroup, it appears that packets are received on all interfaces without the ability to control this at the interface level. Is this correct? If not is there a way to configure NWConnectionGroup to receive packets on all interfaces?
3. Sending Behavior
During the send operation, it appears that the data is sent through any one of the available interfaces, and there doesn't seem to be an option to configure it to send through all available endpoints. Is there a way to enable sending data through all available endpoints?
Any insights, guidance, or solutions to these issues would be greatly appreciated. Has anyone else encountered similar problems or found workarounds for these limitations?
Thank you for your assistance and support.
Thanks,
Harshal
Post not yet marked as solved
Hi I'm getting this issue:
Crashed: com.apple.network.connections
0 libsystem_kernel.dylib 0xa974 __pthread_kill + 8
1 libsystem_pthread.dylib 0x60ec pthread_kill + 268
2 libsystem_c.dylib 0x75b80 abort + 180
3 libsystem_malloc.dylib 0x2bc68 malloc_vreport + 896
4 libsystem_malloc.dylib 0x2bf10 malloc_zone_error + 104
5 libsystem_malloc.dylib 0x21a44 nanov2_guard_corruption_detected + 44
6 libsystem_malloc.dylib 0x7f84 nanov2_find_block_and_allocate + 402
7 libc++abi.dylib 0x16b84 operator new(unsigned long) + 52
8 Network 0x7e8c void std::__1::vector<nw_object_wrapper_t, std::__1::allocator<nw_object_wrapper_t> >::__emplace_back_slow_path<nw_object*&>(nw_object*&) + 124
9 Network 0x7dd8 nw_array_append + 280
10 Network 0xc3d0 __nw_resolver_insert_endpoint_locked_block_invoke + 1036
11 Network 0xbd80 nw_array_apply + 124
12 Network 0x77250 nw_resolver_insert_endpoint_locked + 256
13 Network 0x770b8 nw_resolver_insert_address + 1356
14 Network 0x29a850 __nw_resolver_create_dns_getaddrinfo_locked_block_invoke.187 + 7836
15 libdns_services.dylib 0x1000 ___dnssd_getaddrinfo_activate_block_invoke + 216
16 libdispatch.dylib 0x3dd4 _dispatch_client_callout + 20
17 libdispatch.dylib 0x72d8 _dispatch_continuation_pop + 600
18 libdispatch.dylib 0x1b1c8 _dispatch_source_latch_and_call + 420
19 libdispatch.dylib 0x19d8c _dispatch_source_invoke + 832
20 libdispatch.dylib 0xd284 _dispatch_workloop_invoke + 1756
21 libdispatch.dylib 0x16cb4 _dispatch_root_queue_drain_deferred_wlh + 288
22 libdispatch.dylib 0x16528 _dispatch_workloop_worker_thread + 404
23 libsystem_pthread.dylib 0x1f20 _pthread_wqthread + 288
24 libsystem_pthread.dylib 0x1fc0 start_wqthread + 8
Post not yet marked as solved
I need to obtain data through mqtt and subscription? Is there any idea or framework ?
Think you
Post not yet marked as solved
I would like to determine why communication with the server is failing.
The following situation.
・An SSL error occurs when communicating with the server.
ATS failed system trust
Connection 13: system TLS Trust evaluation failed(-9802)
Connection 13: TLS Trust encountered error 3:-9802
Connection 13: encountered error(3:-9802)
nw_connection_copy_connected_local_endpoint_block_invoke [C14] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection
nw_connection_copy_connected_remote_endpoint_block_invoke [C14] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection
nw_connection_copy_protocol_metadata_internal_block_invoke [C14] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection
Task <07B896CB-44B4-44BC-87B4-EB786D5B25DA>.<10> HTTP load failed, 0/0 bytes (error code: -1200 [3:-9802])
Task <07B896CB-44B4-44BC-87B4-EB786D5B25DA>.<10> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "SSLエラーが起きたため、サーバへのセキュリティ保護された接続を確立できません。" UserInfo={NSLocalizedRecoverySuggestion=それでもサーバに接続しますか?, _kCFStreamErrorDomainKey=3, NSErrorPeerCertificateChainKey=(
"<cert(0x1091bca00) s: Default Company Ltd i: Default Company Ltd>"
), NSErrorClientCertificateStateKey=0, NSErrorFailingURLKey=https://xxxx, NSErrorFailingURLStringKey=https://xxxx, NSUnderlyingError=0x2838e96e0 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x28073aa80>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x1091bca00) s: Default Company Ltd i: Default Company Ltd>"
)}}, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <07B896CB-44B4-44BC-87B4-EB786D5B25DA>.<10>"
), _kCFStreamErrorCodeKey=-9802, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <07B896CB-44B4-44BC-87B4-EB786D5B25DA>.<10>, NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x28073aa80>, NSLocalizedDescription=SSLエラーが起きたため、サーバへのセキュリティ保護された接続を確立できません。}
・I checked that server for ATS (App Transport Security) support with the nscurl command and found that it supported it without any problems.
・The error content changes when an ATS exception is handled by the iOS client.
Connection 35: default TLS Trust evaluation failed(-9807)
Connection 35: TLS Trust encountered error 3:-9807
Connection 35: encountered error(3:-9807)
nw_connection_copy_connected_local_endpoint_block_invoke [C36] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection
nw_connection_copy_connected_remote_endpoint_block_invoke [C36] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection
nw_connection_copy_protocol_metadata_internal_block_invoke [C36] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection
Task <882E38EE-4E0D-4428-A4BE-709BB8448530>.<34> HTTP load failed, 0/0 bytes (error code: -1202 [3:-9807])
Task <882E38EE-4E0D-4428-A4BE-709BB8448530>.<34> finished with error [-1202] Error Domain=NSURLErrorDomain Code=-1202 "このサーバの証明書は無効です。"xxxx"に偽装したサーバに接続している可能性があり、機密情報が漏えいするおそれがあります。" UserInfo={NSLocalizedRecoverySuggestion=それでもサーバに接続しますか?, _kCFStreamErrorDomainKey=3, NSErrorPeerCertificateChainKey=(
"<cert(0x14c2e9000) s: Default Company Ltd i: Default Company Ltd>"
), NSErrorClientCertificateStateKey=0, NSErrorFailingURLKey=https://xxxx, NSErrorFailingURLStringKey=https://xxxx, NSUnderlyingError=0x281d86310 {Error Domain=kCFErrorDomainCFNetwork Code=-1202 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x2823f7200>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9807, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9807, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x14c2e9000) s: Default Company Ltd i: Default Company Ltd>"
)}}, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <882E38EE-4E0D-4428-A4BE-709BB8448530>.<34>"
), _kCFStreamErrorCodeKey=-9807, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <882E38EE-4E0D-4428-A4BE-709BB8448530>.<34>, NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x2823f7200>, NSLocalizedDescription=このサーバの証明書は無効です。"xxxx"に偽装したサーバに接続している可能性があり、機密情報が漏えいするおそれがあります。}
・Client can communicate normally when client is not iOS (also Safari)
・Even on iOS, after many failed attempts, the communication suddenly succeeds (after success, the session cache is consulted).
The server appears to be fine, but that said, iOS is failing to communicate.
What are possible cases like this?
Post not yet marked as solved
I'm trying to use rvictl but here's what I run into
> rvictl
Could not get list of devices
> sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.rpmuxd.plist
Load failed: 5: Input/output error
Try running `launchctl bootstrap` as root for richer errors.
> ls /System/Library/LaunchDaemons/com.apple.rpmuxd.plist
ls: /System/Library/LaunchDaemons/com.apple.rpmuxd.plist: No such file or directory
XCode version 15.3
MacOS Sonoma 14.4.1
Apple M1 Max
Hey everyone,
I'm tackling a scenario where I need to fetch a comprehensive list of both IPv4 and IPv6 addresses linked to a particular DNS. I know about the POSIX function getaddrinfo(), but I'm on the lookout for an asynchronous solution. Previously, I could've used CFHost, but unfortunately, it's been deprecated. Any suggestions or insights on how to achieve this asynchronously would be greatly appreciated!
Thanks,
Harshal
Post not yet marked as solved
Users have reported unusually high data usage with my app.
So to investigate I have profiled in instruments. My app as expected in using minimal data. However in instruments I see an "Unknown" process. Which sends around 1mb of data every 2 seconds.
Can anyone explain what unknown process is? Sorry my question is vague but I'm at the beginning of understanding the instruments outputs so your help is so very much appreciated.
Post not yet marked as solved
We've released our app on the App Store and are facing the following issue: Some users are unable to connect to the server with the app, and the "Cellular Data" settings for our app are missing in the system settings.
The app is developer on Qt framework (qt.io)
This is how it should be
This is what some users reporting - app unable to make requests to the server by https (request timeout)
Why it happening?
Any tips how to fix?
Post not yet marked as solved
Hi,
I observed some unexpected behavior and hope that someone can enlighten me as to what this is about:
mDNSResponder prepends IP / network based default search domains that are checked before any other search domain. E.g. 0.1.168.192.in-addr.arpa. would be used for an interface with an address in the the 192.168.1.0/24 subnet. This is done for any configured non-link-local IP address.
I tried to find any mention of an approach like this in RFCs but couldn't spot anything.
Please note that this is indeed a search domain and different from reverse-DNS lookups.
Example output of tcpdump for ping devtest:
10:02:13.850802 IP (tos 0x0, ttl 64, id 43461, offset 0, flags [none], proto UDP (17), length 92)
192.168.1.2.52319 > 192.168.1.1.53: 54890+ [1au] A? devtest.0.1.168.192.in-addr.arpa. (64)
I was able to identify the code that adds those default IP subnet based search domains but failed to spot any indication as to what this is about: https://github.com/apple-oss-distributions/mDNSResponder/blob/d5029b5/mDNSMacOSX/mDNSMacOSX.c#L4171-L4211
Does anyone here have an ideas as to what this might be about?
Post not yet marked as solved
For important background information, read Extra-ordinary Networking before reading this.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Network Interface Statistics
One FAQ when it comes to network interfaces is “How do I get network interface statistics?” There are numerous variants of this:
Some folks ask about specific network interfaces: “How do I get cellular data usage?”
Some folks are interested in per-app statistics: “How do I get cellular data usage statistics for each app?” or “How do I get cellular data usage statistics for my app?”
Some folks only care about recent statistics: “How can I tell how much network data this operation generated?”
Some folks care about usage across restarts: “How do I get the cellular data usage shown in the Settings app on iOS?”
Most of these questions have no supported answers. However, there are a some supported techniques available. This post explains those techniques, and their limitations.
MetricKit
To get network usage for your app, use MetricKit. Specifically, look at the MXNetworkTransferMetric payload.
MetricKit has a number of design points:
You only get metrics for your app.
You get metrics periodically; you can’t monitor these statistics in real time.
Legacy Techniques
The getifaddrs routine returns rudimentary network interface statistics. See the getifaddrs man page and the struct if_data definition in <net/if_var.h>. Here’s an example of how you might use this:
func legacyNetworkInterfaceStatisticsForInterfaceNamed(_ name: String) -> LegacyNetworkInterfaceStatistics? {
var addrList: UnsafeMutablePointer<ifaddrs>? = nil
let err = getifaddrs(&addrList)
// In theory we could check `errno` here but, honestly, what are gonna
// do with that info?
guard
err >= 0,
let first = addrList
else { return nil }
defer { freeifaddrs(addrList) }
return sequence(first: first, next: { $0.pointee.ifa_next })
.compactMap { addr in
guard
let nameC = addr.pointee.ifa_name,
name == String(cString: nameC),
let sa = addr.pointee.ifa_addr,
sa.pointee.sa_family == AF_LINK,
let data = addr.pointee.ifa_data
else { return nil }
return LegacyNetworkInterfaceStatistics(if_data: data.assumingMemoryBound(to: if_data.self).pointee)
}
.first
}
struct LegacyNetworkInterfaceStatistics {
var packetsIn: UInt32 // ifi_ipackets
var packetsOut: UInt32 // ifi_opackets
var bytesIn: UInt32 // ifi_ibytes
var bytesOut: UInt32 // ifi_obytes
}
extension LegacyNetworkInterfaceStatistics {
init(if_data ifData: if_data) {
self.packetsIn = ifData.ifi_ipackets
self.packetsOut = ifData.ifi_opackets
self.bytesIn = ifData.ifi_ibytes
self.bytesOut = ifData.ifi_obytes
}
}
This is a legacy interface. macOS inherited this API from its ancestor platforms, and iOS inherited it from macOS. That history means that the API has significant limitations:
The counters reset each time the device restarts.
The counters are represented as a UInt32, and so wrap at 4 GiB [1].
Due to its legacy nature, there’s little point filing an enhancement request against this API.
[1] The <net/if_var.h> header defines an if_data64 structure, but there’s no supported way to get that value on Apple platforms.
Limitations
When it comes to network interface statistics, certain tasks have no supported solutions:
Getting per-app statistics
Getting whole device statistics that persist across a restart
Getting real-time statistics for your app that persist across a restart
If you need one of these features, feel free to file an enhancement request for it. In your ER:
Be specific about the platforms you need this on [1].
Make sure that your request is aligned with that platforms privacy constraints. For example, iOS isolates your app from other apps, so you’re unlikely to get an API that returns per-app statistics for all apps on the system.
Supply a clear justification for why this is important to your product.
[1] If it’s macOS, be clear about:
Whether your app is sandboxed or not.
Whether it’s a Mac Catalyst.
Or running via iOS Apps on Mac.
Post not yet marked as solved
The man page for getifaddrs states:
The ifa_data field references address family specific data. For AF_LINK addresses it
contains a pointer to the struct if_data (as defined in include file <net/if.h>) which
contains various interface attributes and statistics. For all other address families, it
contains a pointer to the struct ifa_data (as defined in include file <net/if.h>) which
contains per-address interface statistics.
I assume that "AF_LINK address" is the one that has AF_LINK in the p.ifa_addr.sa_family field.
However I do not see "struct ifa_data" anywehere. Is this a documentation bug and if so how do I read this documentation right?
Post not yet marked as solved
Hi,
We recently released a version of our app where we use 'NWParameters.PrivacyContext'.
On iOS 17.4 and iOS 17.4.1 the app crashes with a following crash:
Distributor ID: com.apple.AppStore
Hardware Model: iPhone12,1
Process: <app>
Path: <path to app>
Identifier: <bundle id>
Version: <version>
AppStoreTools: 15E204
AppVariant: 1:iPhone12,1:15
Code Type: ARM-64 (Native)
Role: Foreground
Parent Process: launchd [1]
Coalition: <our bundle id> [4899]
Date/Time: 2024-04-29 01:50:13.4113 +0300
Launch Time: 2024-04-29 01:13:47.6252 +0300
OS Version: iPhone OS 17.4.1 (21E236)
Release Type: User
Baseband Version: 5.00.00
Report Version: 104
Exception Type: EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000054
Exception Codes: 0x0000000000000001, 0x0000000000000054
VM Region Info: 0x54 is not in any region. Bytes before following region: 4334124972
REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL
UNUSED SPACE AT START
--->
__TEXT 102558000-1063e4000 [ 62.5M] r-x/r-x SM=COW
<path to app>
Termination Reason: SIGNAL 11 Segmentation fault: 11
Terminating Process: exc handler [24308]
Triggered by Thread: 18
Kernel Triage:
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
VM - (arg = 0x3) mach_vm_allocate_kernel failed within call to vm_map_enter
Thread 18 name:
Thread 18 Crashed:
0 libdispatch.dylib 0x00000001a573b7d8 dispatch_async + 192 (queue.c:940)
1 Network 0x000000019ddbdb38 nw_queue_context_async + 76 (queue.m:87)
2 Network 0x000000019e512748 invocation function for block in nw_socket_init_socket_event_source(nw_socket*, unsigned int) + 1488 (protocol_socket.cpp:4351)
3 libdispatch.dylib 0x00000001a5736dd4 _dispatch_client_callout + 20 (object.m:576)
4 libdispatch.dylib 0x00000001a573a2d8 _dispatch_continuation_pop + 600 (queue.c:321)
5 libdispatch.dylib 0x00000001a574e1c8 _dispatch_source_latch_and_call + 420 (source.c:596)
6 libdispatch.dylib 0x00000001a574cd8c _dispatch_source_invoke + 832 (source.c:961)
7 libdispatch.dylib 0x00000001a5740284 _dispatch_workloop_invoke + 1756 (queue.c:4570)
8 libdispatch.dylib 0x00000001a5749cb4 _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:6998)
9 libdispatch.dylib 0x00000001a5749528 _dispatch_workloop_worker_thread + 404 (queue.c:6592)
10 libsystem_pthread.dylib 0x00000001f981cf20 _pthread_wqthread + 288 (pthread.c:2665)
11 libsystem_pthread.dylib 0x00000001f981cfc0 start_wqthread + 8 (:-1)
Thread 18 crashed with ARM Thread State (64-bit):
x0: 0x0000000301a922e0 x1: 0x000000032471a720 x2: 0x0000000000000000 x3: 0x00000003015e2300
x4: 0x0000000000000003 x5: 0x00000000000022e0 x6: 0x0000000172462ef0 x7: 0x000000000000008b
x8: 0x00000000000008ff x9: 0x0000000000000000 x10: 0x0000000000010000 x11: 0x0000000000000020
x12: 0x00000003016f3854 x13: 0x00000000001ff800 x14: 0x00000000000007fb x15: 0x0000000089800118
x16: 0x00000001a573511c x17: 0x000000019e514740 x18: 0x0000000000000000 x19: 0x0000000000000000
x20: 0x0000000308eae8c0 x21: 0x000000032471a730 x22: 0x000000032471b0e0 x23: 0x000000000000e023
x24: 0x0000000172463085 x25: 0x000000002b1d034c x26: 0x0000000000000800 x27: 0x0000000000000000
x28: 0x0000000000000000 fp: 0x000000032471a6b0 lr: 0xad5ba301a573b750
sp: 0x000000032471a690 pc: 0x00000001a573b7d8 cpsr: 0x80000000
esr: 0x92000006 (Data Abort) byte read Translation fault
What could be the reason for it?