General:
Forums subtopic: App & System Services > Networking
TN3151 Choosing the right networking API
Networking Overview document — Despite the fact that this is in the archive, this is still really useful.
TLS for App Developers forums post
Choosing a Network Debugging Tool documentation
WWDC 2019 Session 712 Advances in Networking, Part 1 — This explains the concept of constrained networking, which is Apple’s preferred solution to questions like How do I check whether I’m on Wi-Fi?
TN3135 Low-level networking on watchOS
TN3179 Understanding local network privacy
Adapt to changing network conditions tech talk
Understanding Also-Ran Connections forums post
Extra-ordinary Networking forums post
Foundation networking:
Forums tags: Foundation, CFNetwork
URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms.
Network framework:
Forums tag: Network
Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms.
Building a custom peer-to-peer protocol sample code (aka TicTacToe)
Implementing netcat with Network Framework sample code (aka nwcat)
Configuring a Wi-Fi accessory to join a network sample code
Moving from Multipeer Connectivity to Network Framework forums post
Network Extension (including Wi-Fi on iOS):
See Network Extension Resources
Wi-Fi Fundamentals
TN3111 iOS Wi-Fi API overview
Wi-Fi Aware framework documentation
Wi-Fi on macOS:
Forums tag: Core WLAN
Core WLAN framework documentation
Wi-Fi Fundamentals
Secure networking:
Forums tags: Security
Apple Platform Security support document
Preventing Insecure Network Connections documentation — This is all about App Transport Security (ATS).
Available trusted root certificates for Apple operating systems support article
Requirements for trusted certificates in iOS 13 and macOS 10.15 support article
About upcoming limits on trusted certificates support article
Apple’s Certificate Transparency policy support article
What’s new for enterprise in iOS 18 support article — This discusses new key usage requirements.
Technote 2232 HTTPS Server Trust Evaluation
Technote 2326 Creating Certificates for TLS Testing
QA1948 HTTPS and Test Servers
Miscellaneous:
More network-related forums tags: 5G, QUIC, Bonjour
On FTP forums post
Using the Multicast Networking Additional Capability forums post
Investigating Network Latency Problems forums post
WirelessInsights framework documentation
iOS Network Signal Strength
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Networking
RSS for tagExplore the networking protocols and technologies used by the device to connect to Wi-Fi networks, Bluetooth devices, and cellular data services.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hi, I am new to swift and IOS development, I was developing an app which can be used to communicating between Apple Watch and iPhone.
Something strange occurred when I was trying to observe the status of the message(UserInfo) sent by func transferUserInfo(_ userInfo: [String : Any] = [:]) -> WCSessionUserInfoTransfer.
I was trying to observe isTransferring(a boolean value) in WCSessionUserInfoTransfer which was returned by the function mentioned above, but it seems cannot be updated even if the message queue was empty, it seems to always be True.
Here is my sample code:
let transfer = session.transferUserInfo(message)
if transfer.isTransferring {
Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { timer in
print("Queued message count: \(self.session.outstandingUserInfoTransfers.count), isTransferring:\(transfer.isTransferring)")
if !transfer.isTransferring {
timer.invalidate()
// irrelevant codes...
}
}
} else {
// other irrelevant codes...
}
Appreciate if anyone can help me out of this problem.
Best wishes.
Esim activation. Assuming I already have card data, I use the universal link https://esimsetup.apple.com/esim_qrcode_provisioning?carddata= to install it.
However, it always ends up in the system Settings app.
The flow: 1. Click the link -> 2. Redirect to Settings -> 3. Show activation dialog.
Is there anyway to make the activation flow stay within the app? I couldn't find any documentation for that.
This is an example from Revolut app, where the whole flow above happens without leaving the app.
We are using PacketTunnel as system extension to establish vpn tunnel. The flow is like:
Create a PacketTunnelProvide to establish vpn
When tunnel gets connected add excludedRoutes by calling setTunnelNetworkSettings().
Result: The routing table is not getting updated with new excludeRoutes entries.
As per setTunnelNetworkSettings() documentation:
"This function is called by tunnel provider implementations to set the network settings of the tunnel, including IP routes, DNS servers, and virtual interface addresses depending on the tunnel type. Subclasses should not override this method. This method can be called multiple times during the lifetime of a particular tunnel. It is not necessary to call this function with nil to clear out the existing settings before calling this function with a non-nil configuration."
So we believe setTunnelNetworkSettings() should be able to set new excludeRoutes. We could see we are passing correct entries to setTunnelNetworkSettings():
{
tunnelRemoteAddress = 10.192.229.240
DNSSettings = {
protocol = cleartext
server = (
10.192.230.211,
192.168.180.15,
)
matchDomains = (
,
)
matchDomainsNoSearch = NO
}
IPv4Settings = {
configMethod = manual
addresses = (
100.100.100.17,
)
subnetMasks = (
255.255.255.255,
)
includedRoutes = (
{
destinationAddress = 1.1.1.1
destinationSubnetMask = 255.255.255.255
gatewayAddress = 100.100.100.17
},
{
destinationAddress = 2.2.2.0
destinationSubnetMask = 255.255.255.255
gatewayAddress = 100.100.100.17
},
{
destinationAddress = 11.11.11.0
destinationSubnetMask = 255.255.255.0
gatewayAddress = 100.100.100.17
},
)
excludedRoutes = (
{
destinationAddress = 170.114.52.2
destinationSubnetMask = 255.255.255.255
},
)
overridePrimary = NO
}
MTU = 1298
}
The problem is present on macOS Sequoia 15.2.
Is it a known issue? Did anyone else faced this issue?
Android phones supporting Wi-Fi Aware 4.0 should be able to connect with iPhones (iOS 26). For testing, we selected two Samsung S25 devices, which support Wi-Fi Aware 4.0.
Issues we are facing
Android as Publisher, iOS as Subscriber, iOS cannot discover the service. Log shows: Discovery: Dropping event, 02:14:60:76:a6:0f missing DCEA attribute.
iOS as Publisher, Android as Subscriber.Android can discover the service.However, the PIN code is not displayed on iOS.
From the packet capture, the publish packet does not contain the DCEA field. However, Android-to-Android devices can still pair normally, and the subsequent PASN packets include the DCEA field. It seems that the Wi-Fi Alliance only requires the DCEA to be present in the PASN packets.
iOS cannot discover Android devices or complete pairing — is this caused by the DCEA field, or by other reasons?
Topic:
App & System Services
SubTopic:
Networking
I am developing an application that processes a video file stored on a server. I use URLSessionDataTask with a delegate handler to download the file.
It is not necessary to download the entire file at once. Instead, I can load small chunks of the file as needed. This approach helps minimize memory consumption.
I am trying to design a network layer that supports this behavior. Ideally, I would like to have an interface similar to:
func readMoreData(length: Int) async throws -> Data
Problems I Encountered:
It seems that URLSessionDataTask does not allow controlling how many bytes will be downloaded. It always downloads the entire request.
If I call suspend on URLSessionDataTask, the network activity does not stop, and the file keeps downloading.
If I upgrade the dataTask to a StreamTask, the file still downloads, though reading bytes can be done through the StreamTask API.
I would prefer behavior similar to AsyncHTTPClient (a Swift Server library) or Network Framework. These frameworks allow controlling the number of bytes downloaded at a time. Unfortunately, they do not fit the specific requirements of my project.
Am I correct in understanding that controlling the download process is not possible with URLSessionDataTask?
As a possible solution, I am considering using HTTP Range Requests, though this would increase the number of additional server requests, which I would like to avoid.
Topic:
App & System Services
SubTopic:
Networking
This post is part of the Local Network Privacy FAQ.
What operations require local network access?
The general rule is that outgoing traffic to a local network address requires that the user grant your app local network access. Common scenarios include:
Making an outgoing TCP connection — yes
Listening for and accepting incoming TCP connections — no
Sending a UDP unicast — yes
Sending a UDP multicast — yes
Sending a UDP broadcast — yes
Connecting a UDP socket — yes
Receiving an incoming UDP unicast — no
Receiving an incoming UDP multicast — yes
Receiving an incoming UDP broadcast — yes
These TCP and UDP checks are done at the lowest levels of the system and thus apply to all networking APIs. This includes Network framework, BSD Sockets, NSStream, and NSURLSession, and any other protocols that you layer on top of those.
IMPORTANT Receiving an incoming UDP multicast or broadcast does not currently require local network access but, because we hope to change that in a future update, our advice right now is that you write your code as if did (r. 69792887, 70017649).
Resolving link-local DNS names (those ending with local, per RFC 6762) requires local network access. Again, this check applies to a wide variety of APIs including <dns_sd.h>, <net_db.h>, Network framework, NSStream, and NSURLSession.
Finally, all Bonjour operations require local network access:
Registering a service with Bonjour — yes
Browsing for Bonjour services — yes
Resolving a Bonjour service — yes
Again, these checks apply to all APIs that use Bonjour, including <dns_sd.h>, Network framework, NSNetService, and Multipeer Connectivity.
Note You must declare the Bonjour service types you use in your Info.plist. See FAQ-14 How do I map my Multipeer Connectivity service type to an entry in the Bonjour services property? for details.
Bonjour-based services where you don’t see any details of the network do not require local network access. These include:
AirPlay — no
Printing via UIKit — no
Back to the FAQ
On "Accessory Interface Specification CarPlay Addendum R10", it says that it is recommended that the accessory uses a MIMO (2x2) hardware configuration, does this imply that WiFi 5 and SISO (1X1) will be phased out in the near future?
When will WiFi 6 MIMO (2x2) become mandatory?
On "Accessory Interface Specification CarPlay Addendum R10", it says that Spatial Audio is mandatory. However, for aftermarket in-vehicle infotainment (IVI) system due to the number of speakers are less than 6, is it allowed not to support spatial audio for this type of aftermarket IVI system?
This issue has cropped up many times here on DevForums. Someone recently opened a DTS tech support incident about it, and I used that as an opportunity to post a definitive response here.
If you have questions or comments about this, start a new thread and tag it with Network so that I see it.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
iOS Network Signal Strength
The iOS SDK has no general-purpose API that returns Wi-Fi or cellular signal strength in real time. Given that this has been the case for more than 10 years, it’s safe to assume that it’s not an accidental omission but a deliberate design choice.
For information about the Wi-Fi APIs that are available on iOS, see TN3111 iOS Wi-Fi API overview.
Network performance
Most folks who ask about this are trying to use the signal strength to estimate network performance. This is a technique that I specifically recommend against. That’s because it produces both false positives and false negatives:
The network signal might be weak and yet your app has excellent connectivity. For example, an iOS device on stage at WWDC might have terrible WWAN and Wi-Fi signal but that doesn’t matter because it’s connected to the Ethernet.
The network signal might be strong and yet your app has very poor connectivity. For example, if you’re on a train, Wi-Fi signal might be strong in each carriage but the overall connection to the Internet is poor because it’s provided by a single over-stretched WWAN.
The only good way to determine whether connectivity is good is to run a network request and see how it performs. If you’re issuing a lot of requests, use the performance of those requests to build a running estimate of how well the network is doing. Indeed, Apple practices what we preach here: This is exactly how HTTP Live Streaming works.
Remember that network performance can change from moment to moment. The user’s train might enter or leave a tunnel, the user might step into a lift, and so on. If you build code to estimate the network performance, make sure it reacts to such changes.
Keeping all of the above in mind, iOS 26 beta has two new APIs related to this issue:
Network framework now offers a linkQuality property. See this post for my take on how to use this effectively.
The WirelessInsights framework can notify you of anticipated WWAN condition changes.
But what about this code I found on the ’net?
Over the years various folks have used various unsupported techniques to get around this limitation. If you find code on the ’net that, say, uses KVC to read undocumented properties, or grovels through system logs, or walks the view hierarchy of the status bar, don’t use it. Such techniques are unsupported and, assuming they haven’t broken yet, are likely to break in the future.
But what about Hotspot Helper?
Hotspot Helper does have an API to read Wi-Fi signal strength, namely, the signalStrength property. However, this is not a general-purpose API. Like the rest of Hotspot Helper, this is tied to the specific use case for which it was designed. This value only updates in real time for networks that your hotspot helper is managing, as indicated by the isChosenHelper property.
But what about MetricKit?
MetricKit is so cool. Amongst other things, it supports the MXCellularConditionMetric payload, which holds a summary of the cellular conditions while your app was running. However, this is not a real-time signal strength value.
But what if I’m working for a carrier?
This post is about APIs in the iOS SDK. If you’re working for a carrier, discuss your requirements with your carrier’s contact at Apple.
Revision History
2025-07-02 Updated to cover new features in the iOS 16 beta. Made other minor editorial changes.
2022-12-01 First posted.
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"
Broadcasts and Multicasts, Hints and Tips
I regularly see folks struggle with broadcasts and multicasts on Apple platforms. This post is my attempt to clear up some of the confusion.
This post covers both IPv4 and IPv6. There is, however, a key difference. In IPv4, broadcasts and multicasts are distinct concepts. In contrast, IPv6 doesn’t support broadcast as such; rather, it treats broadcasts as a special case of multicasts. IPv6 does have an all nodes multicast address, but it’s rarely used.
Before reading this post, I suggest you familiarise yourself with IP addresses in general. A good place to start is The Fount of All Knowledge™.
Service Discovery
A lot of broadcast and multicast questions come from folks implementing their own service discovery protocol. I generally recommend against doing that, for the reasons outlined in the Service Discovery section of Don’t Try to Get the Device’s IP Address.
There are, however, some good reasons to implement a custom service discovery protocol. For example, you might be working with an accessory that only supports this custom protocol [1]. If you must implement your own service discovery protocol, read this post and also read the advice in Don’t Try to Get the Device’s IP Address.
IMPORTANT Sometimes I see folks implementing their own version of mDNS. This is almost always a mistake:
If you’re using third-party tooling that includes its own mDNS implementation, it’s likely that this tooling allows you to disable that implementation and instead rely on the Bonjour support that’s built-in to all Apple platforms.
If you’re doing some weird low-level thing with mDNS or DNS-SD, it’s likely that you can do that with the low-level DNS-SD API.
[1] And whose firmware you can’t change! I talk more about this in Working with a Wi-Fi Accessory.
API Choice
Broadcasts and multicasts typically use UDP [1]. TN3151 Choosing the right networking API describes two recommended UDP APIs:
Network framework
BSD Sockets
Our general advice is to prefer Network framework over BSD Sockets, but UDP broadcasts and multicasts are an exception to that rule. Network framework has very limited UDP broadcast support. And while it’s support for UDP multicasts is less limited, it’s still not sufficient for all UDP applications. In cases where Network framework is not sufficient, BSD Sockets is your only option.
[1] It is possible to broadcast and multicast at the Ethernet level, but I almost never see questions about that.
UDP Broadcasts in Network Framework
Historically I’ve claimed that Network framework was useful for UDP broadcasts is very limited circumstances (for example, in the footnote on this post). I’ve since learnt that this isn’t the case. Or, more accurately, this support is so limited (r. 122924701) as to be useless in practice.
For the moment, if you want to work with UDP broadcasts, your only option is BSD Sockets.
UDP Multicasts in Network Framework
Network framework supports UDP multicast using the NWConnectionGroup class with the NWMulticastGroup group descriptor. This support has limits. The most significant limit is that it doesn’t support broadcasts; it’s for multicasts only.
Note This only relevant to IPv4. Remember that IPv6 doesn’t support broadcasts as a separate concept.
There are other limitations, but I don’t have a good feel for them. I’ll update this post as I encounter issues.
Local Network Privacy
Some Apple platforms support local network privacy. This impacts broadcasts and multicasts in two ways:
Broadcasts and multicasts require local network access, something that’s typically granted by the user.
Broadcasts and multicasts are limited by a managed entitlement (except on macOS).
TN3179 Understanding local network privacy has lots of additional info on this topic, including the list of platforms to which it applies.
Send, Receive, and Interfaces
When you broadcast or multicast, there’s a fundamental asymmetry between send and receive:
You can reasonable receive datagrams on all broadcast-capable interfaces.
But when you send a datagram, it has to target a specific interface.
The sending behaviour is the source of many weird problems. Consider the IPv4 case. If you send a directed broadcast, you can reasonably assume it’ll be routed to the correct interface based on the network prefix. But folks commonly send an all-hosts broadcast (255.255.255.255), and it’s not obvious what happens in that case.
Note If you’re unfamiliar with the terms directed broadcast and all-hosts broadcast, see IP address.
The exact rules for this are complex, vary by platform, and can change over time. For that reason, it’s best to write your broadcast code to be interface specific. That is:
Identify the interfaces on which you want to work.
Create a socket per interface.
Bind that socket to that interface.
Note Use the IP_BOUND_IF (IPv4) or IPV6_BOUND_IF (IPv6) socket options rather than binding to the interface address, because the interface address can change over time.
Extra-ordinary Networking has links to other posts which discuss these concepts and the specific APIs in more detail.
Miscellaneous Gotchas
A common cause of mysterious broadcast and multicast problems is folks who hard code BSD interface names, like en0. Doing that might work for the vast majority of users but then fail in some obscure scenarios.
BSD interface names are not considered API and you must not hard code them. Extra-ordinary Networking has links to posts that describe how to enumerate the interface list and identify interfaces of a specific type.
Don’t assume that there’ll be only one interface of a given type. This might seem obviously true, but it’s not. For example, our platforms support peer-to-peer Wi-Fi, so each device has multiple Wi-Fi interfaces.
When sending a broadcast, don’t forget to enable the SO_BROADCAST socket option.
If you’re building a sandboxed app on the Mac, working with UDP requires both the com.apple.security.network.client and com.apple.security.network.server entitlements.
Some folks reach for broadcasts or multicasts because they’re sending the same content to multiple devices and they believe that it’ll be faster than unicasts. That’s not true in many cases, especially on Wi-Fi. For more on this, see the Broadcasts section of Wi-Fi Fundamentals.
Snippets
To send a UDP broadcast:
func broadcast(message: Data, to interfaceName: String) throws {
let fd = try FileDescriptor.socket(AF_INET, SOCK_DGRAM, 0)
defer { try! fd.close() }
try fd.setSocketOption(SOL_SOCKET, SO_BROADCAST, 1 as CInt)
let interfaceIndex = if_nametoindex(interfaceName)
guard interfaceIndex > 0 else { throw … }
try fd.setSocketOption(IPPROTO_IP, IP_BOUND_IF, interfaceIndex)
try fd.send(data: message, to: ("255.255.255.255", 2222))
}
Note These snippet uses the helpers from Calling BSD Sockets from Swift.
To receive UDP broadcasts:
func receiveBroadcasts(from interfaceName: String) throws {
let fd = try FileDescriptor.socket(AF_INET, SOCK_DGRAM, 0)
defer { try! fd.close() }
let interfaceIndex = if_nametoindex(interfaceName)
guard interfaceIndex > 0 else { fatalError() }
try fd.setSocketOption(IPPROTO_IP, IP_BOUND_IF, interfaceIndex)
try fd.setSocketOption(SOL_SOCKET, SO_REUSEADDR, 1 as CInt)
try fd.setSocketOption(SOL_SOCKET, SO_REUSEPORT, 1 as CInt)
try fd.bind("0.0.0.0", 2222)
while true {
let (data, (sender, port)) = try fd.receiveFrom()
…
}
}
IMPORTANT This code runs synchronously, which is less than ideal. In a real app you’d run the receive asynchronously, for example, using a Dispatch read source. For an example of how to do that, see this post.
If you need similar snippets for multicast, lemme know. I’ve got them lurking on my hard disk somewhere (-:
Other Resources
Apple’s official documentation for BSD Sockets is in the man pages. See Reading UNIX Manual Pages. Of particular interest are:
setsockopt man page
ip man page
ip6 man page
If you’re not familiar with BSD Sockets, I strongly recommend that you consult third-party documentation for it. BSD Sockets is one of those APIs that looks simple but, in reality, is ridiculously complicated. That’s especially true if you’re trying to write code that works on BSD-based platforms, like all of Apple’s platforms, and non-BSD-based platforms, like Linux.
I specifically recommend UNIX Network Programming, by Stevens et al, but there are lots of good alternatives.
https://unpbook.com
Revision History
2025-09-01 Fixed a broken link.
2025-01-16 First posted.
Hello, all,
I'm new to iOS development and working on a project with the following setup:
Architecture:
Windows PC running Ubuntu (WSL) hosting a WebSocket Server with self-signed SSL
Python GUI application as a client to control iOS app
iOS app as another client on physical iPhone
Server running on wss://***.***.***.1:8001 (this is the mobile hotspot IP from Windows PC which the iPhone is needed to connect to as well)
Current Status:
✓ Server successfully created and running
✓ Python GUI connects and functions properly
✓ iOS app initially connects and communicates for 30 seconds
✗ iOS connection times out after 30 seconds
✗ Map updates from GUI don't sync to iOS app
Error Message in Xcode terminal:
WebSocket: Received text message
2024-11-25 15:49:03.678384-0800 iVEERS[1465:454666] Task <CD21B8AD-86D9-4984-8C48-8665CD069CC6>.<1> finished with error [-1001] Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2103, _NSURLErrorFailingURLSessionTaskErrorKey=LocalWebSocketTask <CD21B8AD-86D9-4984-8C48-8665CD069CC6>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalWebSocketTask <CD21B8AD-86D9-4984-8C48-8665CD069CC6>.<1>"
), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=wss://***.***.***.1:8001/, NSErrorFailingURLKey=wss://***.***.***.1:8001/, _kCFStreamErrorDomainKey=4}
Technical Details:
Using iOS built-in URLSessionWebSocketTask for WebSocket connection
Self-signed SSL certificate
Transport security settings configured in Info.plist
Map updates use base64 encoded PNG data
Questions:
What's causing the timeout after 30 seconds?
How can I maintain a persistent WebSocket connection?
Why aren't map updates propagating to the iOS client?
Any guidance/suggestions would be greatly appreciated. Please let me know if additional code snippets would help on what I currently have.
I filed FB19631435 about this just now. Basically: starting with 15.6, we've had reports (internally and outternally) that after some period of time, networking fails so badly that it can't even acquire a DHCP lease, and the system needs to be rebooted to fix this. The systems in question all have at least 2 VPN applications installed; ours is a transparent proxy provider, and the affected system also had Crowdstrike's Falcon installed. A customer system reported seemingly identical failures on their systems; they don't have Crowdstrike, but they do have Cyberhaven's.
Has anyone else seen somethng like this? Since it seems to involve three different networking extensions, I'm assuming it's due to an interaction between them, not a bug in any individual one. But what do I know? 😄
I would like to test running some Thread Networking code on my MacOS machine:
import ThreadNetwork
let client = THClient()
let bIsPreferredAvailable = await client.isPreferredAvailable()
but I get some errors when trying to create an instance of the THClient class:
Client: -[THClient connectToXPCService]_block_invoke - CTCS XPC Client is interrupted.
Client: -[THClient getConnectionEntitlementValidity]_block_invoke - clientProxyWithErrorHandler Error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.ThreadNetwork.xpc" UserInfo={NSDebugDescription=connection to service named com.apple.ThreadNetwork.xpc}
Client: -[THClient init] - XPC Client Init Failed
Invalidating XPC connection.
Client: -[THClient getConnectionEntitlementValidity]_block_invoke - clientProxyWithErrorHandler Error: Error Domain=NSCocoaErrorDomain Code=4097 "connection to service named com.apple.ThreadNetwork.xpc" UserInfo={NSDebugDescription=connection to service named com.apple.ThreadNetwork.xpc}
How can I get the code to run?
Hello,
I'd like to find out if macOS Sequoia's MAC Address randomization affects the data (specifically, MAC addresses) we receive from I/O Kit.
For context, I'd like to find out if it affects my Mac App Store receipt validation code in any way.
Thank you,
– Matthias
Topic:
App & System Services
SubTopic:
Networking
Tags:
macOS
IOKit
App Store Receipts
Mac App Store
Hi everyone,
is there any ways we can remove the weak ciphers as part of TLS handshake (TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256)
I checked here but still do not see anyways to print out and change the ciphers suite we want to use
https://forums.developer.apple.com/forums/thread/43230
https://forums.developer.apple.com/forums/thread/700406?answerId=706382022#706382022
Every now and again folks notice that Network framework seems to create an unexpected number of connections on the wire. This post explains why that happens and what you should do about it.
If you have questions or comments, put them in a new thread here on the forums. Use the App & System Services > Networking topic area and the Network tag.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Understanding Also-Ran Connections
Network framework implements the Happy Eyeballs algorithm. That might create more on-the-wire connections than you expect. There are two common places where folks notice this:
When looking at a packet trace
When implementing a listener
Imagine that you’ve implemented a TCP server using NWListener and you connect to it from a client using NWConnection. In many situations there are multiple network paths between the client and the server. For example, on a local network there’s always at least two paths: the link-local IPv6 path and either an infrastructure IPv4 path or the link-local IPv4 path.
When you start your NWConnection, Network framework’s Happy Eyeballs algorithm might [1] start a TCP connection for each of these paths. It then races those connections. The one that connects first is the ‘winner’, and Network framework uses that connection for your traffic. Once it has a winner, the other connections, the also-ran connections, are redundant, and Network framework just closes them.
You can observe this behaviour on the client side by looking in the system log. Many Network framework log entries (subsystem com.apple.network) contain a connection identifier. For example C8 is the eighth connection started by this process. Each connection may have child connections (C8.1, C8.2, …) and grandchild connections (C8.1.1, C8.1.2, …), and so on. You’ll see state transitions for these child connections occurring in parallel. For example, the following log entries show that C8 is racing the connection of two grandchild connections, C8.1.1 and C8.1.2:
type: debug
time: 12:22:26.825331+0100
process: TestAlsoRanConnections
subsystem: com.apple.network
category: connection
message: nw_socket_connect [C8.1.1:1] Calling connectx(…)
type: debug
time: 12:22:26.964150+0100
process: TestAlsoRanConnections
subsystem: com.apple.network
category: connection
message: nw_socket_connect [C8.1.2:1] Calling connectx(…)
Note For more information about accessing the system log, see Your Friend the System Log.
You also see this on the server side, but in this case each connection is visible to your code. When you connect from the client, Network framework calls your listener’s new connection handler with multiple connections. One of those is the winning connection and you’ll receive traffic on it. The others are the also-ran connections, and they close promptly.
IMPORTANT Depending on network conditions there may be no also-ran connections. Or there may be lots of them. If you want to test the also-ran connection case, use Network Link Conditioner to add a bunch of delay to your packets.
You don’t need to write special code to handle also-ran connections. From the perspective of your listener, these are simply connections that open and then immediately close. There’s no difference between an also-ran connection and, say, a connection from a client that immediately crashes. Or a connection generated by someone doing a port scan. Your server must be resilient to such things.
However, the presence of these also-ran connections can be confusing, especially if you’re just getting started with Network framework, and hence this post.
[1] This is “might” because the exact behaviour depends on network conditions. More on that below.
I asked this question of AI and it said that yes it was possible, and gave some sample code
override class func filterConfiguration() -> ILMessageFilterExtensionConfiguration {
let config = ILMessageFilterExtensionConfiguration()
// You can specify multiple network URLs
config.networkURLs = [
URL(string: "https://api1.example.com/filter")!,
URL(string: "https://api2.example.com/filter")!
]
return config
}
And said the OS will try the first, and if there's no response within the first few seconds it'll move onto the second.
However, there is no such class as ILMessageFilterExtensionConfiguration AFAICT, if there is then how to access/use it, if there isn't, then I wonder how the AI counjured it up?
If multiple urls can be specified, then can the extension also specify a particular API to use and switch between them at some point?
When does the OS call filterConfiguration()?
I'm developing in Swift and working on parsing DNS queries. I'm considering using dns_parse_packet, but I noticed that dns_util is deprecated (although it still seems to work in my limited testing).
As far as I know, there isn’t a built-in replacement for this. Is that correct?
On a related note, are there any libraries available for parsing TLS packets—specifically the ClientHello message to extract the Server Name Indication (SNI)—instead of relying on my own implementation?
Related to this post.
IMPORTANT The approach used by this code no longer works. See TN3179 Understanding local network privacy for a replacement.
Currently there is no way to explicitly trigger the local network privacy alert (r. 69157424). However, you can bring it up implicitly by sending dummy traffic to a local network address. The code below shows one way to do this. It finds all IPv4 and IPv6 addresses associated with broadcast-capable network interfaces and sends a UDP datagram to each one. This should trigger the local network privacy alert, assuming the alert hasn’t already been displayed for your app.
Oh, and if Objective-C is more your style, use this code instead.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@apple.com"
import Foundation
/// Does a best effort attempt to trigger the local network privacy alert.
///
/// It works by sending a UDP datagram to the discard service (port 9) of every
/// IP address associated with a broadcast-capable interface. This should
/// trigger the local network privacy alert, assuming the alert hasn’t already
/// been displayed for this app.
///
/// This code takes a ‘best effort’. It handles errors by ignoring them. As
/// such, there’s guarantee that it’ll actually trigger the alert.
///
/// - note: iOS devices don’t actually run the discard service. I’m using it
/// here because I need a port to send the UDP datagram to and port 9 is
/// always going to be safe (either the discard service is running, in which
/// case it will discard the datagram, or it’s not, in which case the TCP/IP
/// stack will discard it).
///
/// There should be a proper API for this (r. 69157424).
///
/// For more background on this, see [Triggering the Local Network Privacy Alert](https://developer.apple.com/forums/thread/663768).
func triggerLocalNetworkPrivacyAlert() {
let sock4 = socket(AF_INET, SOCK_DGRAM, 0)
guard sock4 >= 0 else { return }
defer { close(sock4) }
let sock6 = socket(AF_INET6, SOCK_DGRAM, 0)
guard sock6 >= 0 else { return }
defer { close(sock6) }
let addresses = addressesOfDiscardServiceOnBroadcastCapableInterfaces()
var message = [UInt8]("!".utf8)
for address in addresses {
address.withUnsafeBytes { buf in
let sa = buf.baseAddress!.assumingMemoryBound(to: sockaddr.self)
let saLen = socklen_t(buf.count)
let sock = sa.pointee.sa_family == AF_INET ? sock4 : sock6
_ = sendto(sock, &message, message.count, MSG_DONTWAIT, sa, saLen)
}
}
}
/// Returns the addresses of the discard service (port 9) on every
/// broadcast-capable interface.
///
/// Each array entry is contains either a `sockaddr_in` or `sockaddr_in6`.
private func addressesOfDiscardServiceOnBroadcastCapableInterfaces() -> [Data] {
var addrList: UnsafeMutablePointer<ifaddrs>? = nil
let err = getifaddrs(&addrList)
guard err == 0, let start = addrList else { return [] }
defer { freeifaddrs(start) }
return sequence(first: start, next: { $0.pointee.ifa_next })
.compactMap { i -> Data? in
guard
(i.pointee.ifa_flags & UInt32(bitPattern: IFF_BROADCAST)) != 0,
let sa = i.pointee.ifa_addr
else { return nil }
var result = Data(UnsafeRawBufferPointer(start: sa, count: Int(sa.pointee.sa_len)))
switch CInt(sa.pointee.sa_family) {
case AF_INET:
result.withUnsafeMutableBytes { buf in
let sin = buf.baseAddress!.assumingMemoryBound(to: sockaddr_in.self)
sin.pointee.sin_port = UInt16(9).bigEndian
}
case AF_INET6:
result.withUnsafeMutableBytes { buf in
let sin6 = buf.baseAddress!.assumingMemoryBound(to: sockaddr_in6.self)
sin6.pointee.sin6_port = UInt16(9).bigEndian
}
default:
return nil
}
return result
}
}
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"
Working with a Wi-Fi Accessory
Building an app that works with a Wi-Fi accessory presents specific challenges. This post discusses those challenges and some recommendations for how to address them.
Note While my focus here is iOS, much of the info in this post applies to all Apple platforms.
IMPORTANT iOS 18 introduced AccessorySetupKit, a framework to simplify the discovery and configuration of an accessory. I’m not fully up to speed on that framework myself, but I encourage you to watch WWDC 2024 Session 10203 Meet AccessorySetupKit and read the framework documentation.
IMPORTANT iOS 26 beta introduced WiFiAware, a framework for setting up communication with Wi-Fi Aware accessories. Wi-Fi Aware is an industry standard to securely discover, pair, and communicate with nearby devices. This is especially useful for stand-alone accessories (defined below). For more on this framework, watch WWDC 2025 Session 228 Supercharge device connectivity with Wi-Fi Aware and read the framework documentation.
Accessory Categories
I classify Wi-Fi accessories into three different categories.
A bound accessory is ultimately intended to join the user’s Wi-Fi network. It may publish its own Wi-Fi network during the setup process, but the goal of that process is to get the accessory on to the existing network. Once that’s done, your app interacts with the accessory using ordinary networking APIs.
An example of a bound accessory is a Wi-Fi capable printer.
A stand-alone accessory publishes a Wi-Fi network at all times. An iOS device joins that network so that your app can interact with it. The accessory never provides access to the wider Internet.
An example of a stand-alone accessory is a video camera that users take with them into the field. You might want to write an app that joins the camera’s network and downloads footage from it.
A gateway accessory is one that publishes a Wi-Fi network that provides access to the wider Internet. Your app might need to interact with the accessory during the setup process, but after that it’s useful as is.
An example of this is a Wi-Fi to WWAN gateway.
Not all accessories fall neatly into these categories. Indeed, some accessories might fit into multiple categories, or transition between categories. Still, I’ve found these categories to be helpful when discussing various accessory integration challenges.
Do You Control the Firmware?
The key question here is Do you control the accessory’s firmware? If so, you have a bunch of extra options that will make your life easier. If not, you have to adapt to whatever the accessory’s current firmware does.
Simple Improvements
If you do control the firmware, I strongly encourage you to:
Support IPv6
Implement Bonjour [1]
These two things are quite easy to do — most embedded platforms support them directly, so it’s just a question of turning them on — and they will make your life significantly easier:
Link-local addresses are intrinsic to IPv6, and IPv6 is intrinsic to Apple platforms. If your accessory supports IPv6, you’ll always be able to communicate with it, regardless of how messed up the IPv4 configuration gets.
Similarly, if you support Bonjour, you’ll always be able to find your accessory on the network.
[1] Bonjour is an Apple term for three Internet standards:
RFC 3927 Dynamic Configuration of IPv4 Link-Local Addresses
RFC 6762 Multicast DNS
RFC 6763 DNS-Based Service Discovery
WAC
For a bound accessory, support Wireless Accessory Configuration (WAC). This is a relatively big ask — supporting WAC requires you to join the MFi Program — but it has some huge benefits:
You don’t need to write an app to configure your accessory. The user will be able to do it directly from Settings.
If you do write an app, you can use the EAWiFiUnconfiguredAccessoryBrowser class to simplify your configuration process.
HomeKit
For a bound accessory that works in the user’s home, consider supporting HomeKit. This yields the same onboarding benefits as WAC, and many other benefits as well. Also, you can get started with the HomeKit Open Source Accessory Development Kit (ADK).
Bluetooth LE
If your accessory supports Bluetooth LE, think about how you can use that to improve your app’s user experience. For an example of that, see SSID Scanning, below.
Claiming the Default Route, Or Not?
If your accessory publishes a Wi-Fi network, a key design decision is whether to stand up enough infrastructure for an iOS device to make it the default route.
IMPORTANT To learn more about how iOS makes the decision to switch the default route, see The iOS Wi-Fi Lifecycle and Network Interface Concepts.
This decision has significant implications. If the accessory’s network becomes the default route, most network connections from iOS will be routed to your accessory. If it doesn’t provide a path to the wider Internet, those connections will fail. That includes connections made by your own app.
Note It’s possible to get around this by forcing your network connections to run over WWAN. See Binding to an Interface in Network Interface Techniques and Running an HTTP Request over WWAN. Of course, this only works if the user has WWAN. It won’t help most iPad users, for example.
OTOH, if your accessory’s network doesn’t become the default route, you’ll see other issues. iOS will not auto-join such a network so, if the user locks their device, they’ll have to manually join the network again.
In my experience a lot of accessories choose to become the default route in situations where they shouldn’t. For example, a bound accessory is never going to be able to provide a path to the wider Internet so it probably shouldn’t become the default route. However, there are cases where it absolutely makes sense, the most obvious being that of a gateway accessory.
Acting as a Captive Network, or Not?
If your accessory becomes the default route you must then decide whether to act like a captive network or not.
IMPORTANT To learn more about how iOS determines whether a network is captive, see The iOS Wi-Fi Lifecycle.
For bound and stand-alone accessories, becoming a captive network is generally a bad idea. When the user joins your network, the captive network UI comes up and they have to successfully complete it to stay on the network. If they cancel out, iOS will leave the network. That makes it hard for the user to run your app while their iOS device is on your accessory’s network.
In contrast, it’s more reasonable for a gateway accessory to act as a captive network.
SSID Scanning
Many developers think that TN3111 iOS Wi-Fi API overview is lying when it says:
iOS does not have a general-purpose API for Wi-Fi scanning
It is not.
Many developers think that the Hotspot Helper API is a panacea that will fix all their Wi-Fi accessory integration issues, if only they could get the entitlement to use it.
It will not.
Note this comment in the official docs:
NEHotspotHelper is only useful for hotspot integration. There are both technical and business restrictions that prevent it from being used for other tasks, such as accessory integration or Wi-Fi based location.
Even if you had the entitlement you would run into these technical restrictions. The API was specifically designed to support hotspot navigation — in this context hotspots are “Wi-Fi networks where the user must interact with the network to gain access to the wider Internet” — and it does not give you access to on-demand real-time Wi-Fi scan results.
Many developers look at another developer’s app, see that it’s displaying real-time Wi-Fi scan results, and think there’s some special deal with Apple that’ll make that work.
There is not.
In reality, Wi-Fi accessory developers have come up with a variety of creative approaches for this, including:
If you have a bound accessory, you might add WAC support, which makes this whole issue go away.
In many cases, you can avoid the need for Wi-Fi scan results by adopting AccessorySetupKit.
You might build your accessory with a barcode containing the info required to join its network, and scan that from your app. This is the premise behind the Configuring a Wi-Fi Accessory to Join the User’s Network sample code.
You might configure all your accessories to have a common SSID prefix, and then take advantage of the prefix support in NEHotspotConfigurationManager. See Programmatically Joining a Network, below.
You might have your app talk to your accessory via some other means, like Bluetooth LE, and have the accessory scan for Wi-Fi networks and return the results.
Programmatically Joining a Network
Network Extension framework has an API, NEHotspotConfigurationManager, to programmatically join a network, either temporarily or as a known network that supports auto-join. For the details, see Wi-Fi Configuration.
One feature that’s particularly useful is it’s prefix support, allowing you to create a configuration that’ll join any network with a specific prefix. See the init(ssidPrefix:) initialiser for the details.
For examples of how to use this API, see:
Configuring a Wi-Fi Accessory to Join the User’s Network — It shows all the steps for one approach for getting a non-WAC bound accessory on to the user’s network.
NEHotspotConfiguration Sample — Use this to explore the API in general.
Secure Communication
Users expect all network communication to be done securely. For some ideas on how to set up a secure connection to an accessory, see TLS For Accessory Developers.
Revision History
2025-06-19 Added a preliminary discussion of Wi-Fi Aware.
2024-09-12 Improved the discussion of AccessorySetupKit.
2024-07-16 Added a preliminary discussion of AccessorySetupKit.
2023-10-11 Added the HomeKit section. Fixed the link in Secure Communication to point to TLS For Accessory Developers.
2023-07-23 First posted.