Bonjour, also known as zero-configuration networking, enables automatic discovery of devices and services on a local network using industry standard.

Posts under Bonjour tag

47 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Bonjour Conformance Test - Multiple Instance in Single Device
We are currently working on a zero-configuration networking compliant device thru avahi-daemon. Our Device want to have multiple Instance name for different services. Example InstanceA._ipps._tcp.local. InstanceA._ipp._tcp.local. InstanceB._ipps._tcp.local. InstanceB._ipp._tcp.local. Will BCT confuse this as multiple device connected in the network and cause it to fail? Does Bonjour only allows only a Single Instance name with multiple services?
1
0
45
Apr ’25
On Host Names
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" On Host Names I commonly see questions like How do I get the device’s host name? This question doesn’t make sense without more context. Apple systems have a variety of things that you might consider to be the host name: The user-assigned device name — This is a user-visible value, for example, Guy Smiley. People set this in Settings > General > About > Name. The local host name — This is a DNS name used by Bonjour, for example, guy-smiley.local. By default this is algorithmically derived from the user-assigned device name. On macOS, people can override this in Settings > General > Sharing > Local hostname. The reverse DNS name associated with the various IP addresses assigned to the device’s various network interfaces That last one is pretty much useless. You can’t get a single host name because there isn’t a single IP address. For more on that, see Don’t Try to Get the Device’s IP Address. The other two have well-defined answers, although those answers vary by platform. I’ll talk more about that below. Before getting to that, however, let’s look at the big picture. Big Picture The use cases for the user-assigned device name are pretty clear. I rarely see folks confused about that. Another use case for this stuff is that you’ve started a server and you want to tell the user how to connect to it. I discuss this in detail in Showing Connection Information in an iOS Server. However, most folks who run into problems like this do so because they’re suffering from one of the following misconceptions: The device has a DNS name. Its DNS name is unique. Its DNS name doesn’t change. Its DNS name is in some way useful for networking. Some of these may be true in some specific circumstances, but none of them are true in all circumstances. These issues are not unique to Apple platforms — if you look at the Posix spec for gethostname, it says nothing about DNS! — but folks tend to notice these problems more on Apple platforms because Apple devices are often deployed to highly dynamic network environments. So, before you start using the APIs discussed in this post, think carefully about your assumptions. And if you actually do want to work with DNS, there are two cases to consider: If you’re looking for the local host name, use the APIs discussed above. In other cases, it’s likely that the APIs in this post will not be helpful and you’d be better off focusing on DNS APIs [1]. [1] The API I recommend for this is DNS-SD. See the DNS section in TN3151 Choosing the right networking API. macOS To get the user-assigned device name, call the SCDynamicStoreCopyComputerName(_:_:) function. For example: let userAssignedDeviceName = SCDynamicStoreCopyComputerName(nil, nil) as String? To get the local host name, call the SCDynamicStoreCopyLocalHostName(_:) function. For example: let localHostName = SCDynamicStoreCopyLocalHostName(nil) as String? IMPORTANT This returns just the name label. To form a local host name, append .local.. Both routines return an optional result; code defensively! If you’re displaying these values to the user, use the System Configuration framework dynamic store notification mechanism to keep your UI up to date. iOS and Friends On iOS, iPadOS, tvOS, and visionOS, get the user-assigned device name from the name property on UIDevice. IMPORTANT Access to this is now restricted. For more on that, see the documentation for the com.apple.developer.device-information.user-assigned-device-name entitlement. There is no direct mechanism to get the local host name. Other APIs There are a wide variety of other APIs that purport to return the host name. These include: gethostname The name property on NSHost [1] The hostName property on NSProcessInfo (ProcessInfo in Swift) These are problematic for a number of reasons: They have a complex implementation that makes it hard to predict what value you’ll get back. They might end up trying to infer the host name from the network environment. The existing behaviour is hard to change due to compatibility concerns. Some of them are marked as to-be-deprecated. IMPORTANT The second issue is particularly problematic, because it involves synchronous DNS requests [2]. That’s slow in general. Worse yet, if the network environment is restricted in some way, these calls can be very slow, taking about 30 seconds to time out. Given these problems, it’s generally best to avoid calling these routines at all. [1] It also has a names property, which is a little closer to reality but still not particularly useful. [2] Actually, that’s not true for gethostname. Rather, that call just returns whatever was last set by sethostname. This is always fast. The System Configuration framework infrastructure calls sethostname to update the host name as the system state changes.
0
0
93
Mar ’25
How to use Network.framework
It doesn’t seem like there’s any high level, first-party documentation on how to use what is the recommended API for executing networking logic that you otherwise wouldn’t use URLSession for; which is a lot of things. There’s a sample app, and docs on how to choose the right network API in general, but apparently no high level API docs for Network.framework itself. Am I missing something? How do people learn to use this? Know which classes to use? Know the various ways it can be configured?
4
0
89
Mar ’25
Jetsam memory crash during Network framework usage
I'm using Network Framework to transfer files between 2 devices. The "secondary" device sends file requests to the "primary" device, and the primary sends the files back. When the primary gets the request, it responds like this: do { let data = try Data(contentsOf: filePath) let priSecDataFilePacket = PriSecDataFilePacket(fileName: filename, dataBlob: data) let jsonData = try JSONEncoder().encode(priSecDataFilePacket) let message = NWProtocolFramer.Message(priSecMessageType: PriSecMessageType.priToSecDataFile) let context = NWConnection.ContentContext(identifier: "TransferUtility", metadata: [message]) connection.send(content: encodedJsonToSend, contentContext: context, isComplete: true, completion: .idempotent) } catch { print("\(error)") } It works great, even for hundreds of file requests. The problem arises if some files being requested are extremely large, like 600MB. You can see the memory speedometer on the primary quickly ramp up to the yellow zone, at which point iOS kills the app for high memory use, and you see the Jetsam log. I changed the code to skip JSON encoding the binary file as a test, and that helped a bit, but it still goes too high; the real offender is the step where it loads the 600MB file into the data var: let data = try Data(contentsOf: filePath) If I remark out everything else and just leave that one line, I can still see the memory use spike. As a fix, I'm rewriting this so the secondary requests the file in 5MB chunks by telling the primary a byte range such as "0-5242880" or "5242881-10485760", and then reassembling the chunks on the secondary once they all come in. So far this seems promising, but it's a fair amount of work. My question: Does Network Framework have a built-in way to stream those bytes straight from disk as it sends them? So that I could send all the data in one single request without having to load the bytes into memory?
5
0
361
Mar ’25
browseResultsChangedHandler called multiple times
I'm working on a game that uses NWBrowser and NWListener to create a connection between an iOS and tvOS app. I've got the initial networking up and running and it works perfectly when running in the simulator(s). However, when I run on-device(s), I've found that browseResultsChangedHandler gets called multiple times for what is ostensibly the same service. My browser handler (which runs on iOS) looks like this: browser.browseResultsChangedHandler = { [weak self] results, changes in if let result = browser.browseResults.first { self?.onPeerConnected?(PeerConnection(endpoint: result.endpoint)) } } The first time it gets called, the interface in the NWBrowser.Result is en0, but the 2nd time it gets called, it is en0 AND awdl0. Because my current handling is so naive, this re-invocation ends up with two connections being made to the remote server (the Apple TV). Now, I know that this handler, by its very name, is designed to be called multiple times as things change, so I'm curious as to what strategies I might employ here. Is there any value in tearing down any previous connections and re-connecting using the latest one? Should I just kill the browser as soon as I handle the first one? Just ignore subsequent ones? I'm sure that, to a degree, the answer is probably "it depends"... but I'm curious to see if there might be at least some high-level strategies like "whatever you do, don't do xxxx" or "most apps do yyyy" :-) Thanks.
3
0
334
Feb ’25
Bonjour Conformance Test - SRV PROBING/ANNOUNCEMENTS
Hello, We are currently working on a zero-configuration networking compliant device thru avahi-daemon (for mDNS/DNS-SD handling) and avahi-autoipd (for link-local address configuration). Our test environment setup is: Device Under Test (DUT): Debian 9 Linux avahi-daemon: v0.6.32 avahi-autoipd: v0.6.32 Test Bed: Macmini with macOS Sequoia 15.0 Bonjour Conformance Test v1.5.4 Router: NEC Aterm WR8370N Devices are connected via LAN SRV PROBING/ANNOUNCEMENTS BASIC test failure was encountered in BCT during Multicast-DNS test suite execution. Please see the logs below: ERROR 2025-01-15 19:36:35.792930+0900: Cache flush bit is set in the SRV probes NOTICE 2025-01-15 19:36:35.792946+0900: DEVICE-sERvICE-32\._uSCaNs\._tcp\.lOcaL\.._uscAnS._tCP.loCAL., SEND_CONFLICT_WIN -> SEND_CONFLICT_WIN FAILED (SRV PROBING/ANNOUNCEMENTS BASIC) START (SRV PROBING/ANNOUNCEMENTS) DEBUG_2 2025-01-15 19:36:35.792979+0900: received packet (1137 bytes) DEBUG_2 2025-01-15 19:36:35.792999+0900: srv_cf_probe WARNING 2025-01-15 19:36:35.793022+0900: SRV Probing/Announcements Failed: See runtime output for PROBING and WINNING SIMULTANEOUS PROBE for details. FAILED (SRV PROBING/ANNOUNCEMENTS) We would like to know what causes the above test to fail, is it related to avahi or a an inccorect mDNS service handling wherein the cache flush bit was incorrectly set? Thank you.
2
0
430
Jan ’25
First update to NWBrowser is always ready, irrespective of Local Networking privacy status
I'm trying to detect the state of Local Network privacy on macOS Sequoia via NWBrowser, as recommended in https://developer.apple.com/documentation/technotes/tn3179-understanding-local-network-privacy Regardless of the state of Local Network privacy - undetermined, allowed or denied, NWBrowser receives an update indicating that its in the ready state. Scanning does not seem to trigger the Local Network privacy alert for me - I have to use the other recommended method to trigger the prompt. Enabling or disabling Local Network privacy does not seem to send any updates for NWBrowser. https://developer.apple.com/forums/thread/666431 seems related, and implies that they did receive further updates to NWBrowser. Filed as FB16077972
11
1
707
Jan ’25
Continued connection failure after server connection failure while local network permission pop-up is displayed
We are trying to connect to Webdav. The file server is in the same network. So when we try to connect, the local network permission pop-up is displayed. If the input information is incorrect in the first login attempt when this permission pop-up is displayed, After that, even after fixing the normal connection, we cannot connect or log in with the message "NSURLErrorDomain Code=-1009", "Internet connection is offline." This symptom seems to persist even after rebooting or deleting and deleting the app in the actual distributed app. If you re-debug while debugging Xcode, you can connect normally. (If you do not re-debug, it fails even if you enter the connection information normally.) And it affects local connection, so you cannot connect to any local network server such as SMB or FTP. Also, you cannot browse the server list within the local network. (SMB) Is there a way to initialize the local network status within the app to improve this phenomenon? I tried turning Airplane mode ON/OFF, turning Wi-Fi ON/OFF, and turning local network permissions ON/OFF, but it did not work. Also, this phenomenon seems to be a Sandbox for each app. When connecting to the same local server from an app installed on the same iPhone/iPad device, the above phenomenon does not occur if the first connection is successful. ** Summary ** If you fail to connect to a server on your local network, then you will continue to fail to connect to the local server. This happens even when local network permissions are allowed. The error message is NSURLErrorDomain Code=-1009 The current device is an iPhone device running iOS 18.1.1.
1
0
412
Dec ’24
C++ MacOS include Bonjour
With little knowledge on C++, but help from ChatGPT, I am trying to write a plugin for OBS. I would like to include a bonjour service in the plugin. I assume that the framework is already present on every Mac, but I don't know where it resides, and how to #include it. Anyone can help me here? Thanks in advance https://developer.apple.com/forums/thread/735862?login=true
1
0
415
Dec ’24
Using Network Framework + Bonjour + QUIC + TLS
Hello, I was able to use the TicTackToe code base and modify it such that I have a toggle at the top of the screen that allows me to start / stop the NWBrowser and NWListener. I have it setup so when the browser finds another device it attempts to connect to it. I support N devices / connections. I am able to use the NWParameters extension that is in the TickTackToe game that uses a passcode and TLS. I am able to send messages between devices just fine. Here is what I used extension NWParameters { // Create parameters for use in PeerConnection and PeerListener. convenience init(passcode: String) { // Customize TCP options to enable keepalives. let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 // Create parameters with custom TLS and TCP options. self.init(tls: NWParameters.tlsOptions(passcode: passcode), tcp: tcpOptions) // Enable using a peer-to-peer link. self.includePeerToPeer = true } // Create TLS options using a passcode to derive a preshared key. private static func tlsOptions(passcode: String) -> NWProtocolTLS.Options { let tlsOptions = NWProtocolTLS.Options() let authenticationKey = SymmetricKey(data: passcode.data(using: .utf8)!) let authenticationCode = HMAC<SHA256>.authenticationCode(for: "HI".data(using: .utf8)!, using: authenticationKey) let authenticationDispatchData = authenticationCode.withUnsafeBytes { DispatchData(bytes: $0) } sec_protocol_options_add_pre_shared_key(tlsOptions.securityProtocolOptions, authenticationDispatchData as __DispatchData, stringToDispatchData("HI")! as __DispatchData) sec_protocol_options_append_tls_ciphersuite(tlsOptions.securityProtocolOptions, tls_ciphersuite_t(rawValue: TLS_PSK_WITH_AES_128_GCM_SHA256)!) return tlsOptions } // Create a utility function to encode strings as preshared key data. private static func stringToDispatchData(_ string: String) -> DispatchData? { guard let stringData = string.data(using: .utf8) else { return nil } let dispatchData = stringData.withUnsafeBytes { DispatchData(bytes: $0) } return dispatchData } } When I try to modify it to use QUIC and TLS 1.3 like so extension NWParameters { // Create parameters for use in PeerConnection and PeerListener. convenience init(psk: String) { self.init(quic: NWParameters.quicOptions(psk: psk)) self.includePeerToPeer = true } private static func quicOptions(psk: String) -> NWProtocolQUIC.Options { let quicOptions = NWProtocolQUIC.Options(alpn: ["h3"]) let authenticationKey = SymmetricKey(data: psk.data(using: .utf8)!) let authenticationCode = HMAC<SHA256>.authenticationCode(for: "hello".data(using: .utf8)!, using: authenticationKey) let authenticationDispatchData = authenticationCode.withUnsafeBytes { DispatchData(bytes: $0) } sec_protocol_options_set_min_tls_protocol_version(quicOptions.securityProtocolOptions, .TLSv13) sec_protocol_options_set_max_tls_protocol_version(quicOptions.securityProtocolOptions, .TLSv13) sec_protocol_options_add_pre_shared_key(quicOptions.securityProtocolOptions, authenticationDispatchData as __DispatchData, stringToDispatchData("hello")! as __DispatchData) sec_protocol_options_append_tls_ciphersuite(quicOptions.securityProtocolOptions, tls_ciphersuite_t(rawValue: TLS_AES_128_GCM_SHA256)!) sec_protocol_options_set_verify_block(quicOptions.securityProtocolOptions, { _, _, sec_protocol_verify_complete in sec_protocol_verify_complete(true) }, .main) return quicOptions } // Create a utility function to encode strings as preshared key data. private static func stringToDispatchData(_ string: String) -> DispatchData? { guard let stringData = string.data(using: .utf8) else { return nil } let dispatchData = stringData.withUnsafeBytes { DispatchData(bytes: $0) } return dispatchData } } I get the following errors in the console boringssl_session_handshake_incomplete(241) [C3:1][0x109d0c600] SSL library error boringssl_session_handshake_error_print(44) [C3:1][0x109d0c600] Error: 4459057536:error:100000ae:SSL routines:OPENSSL_internal:NO_CERTIFICATE_SET:/Library/Caches/com.apple.xbs/Sources/boringssl/ssl/tls13_server.cc:882: boringssl_session_handshake_incomplete(241) [C4:1][0x109d0d200] SSL library error boringssl_session_handshake_error_print(44) [C4:1][0x109d0d200] Error: 4459057536:error:100000ae:SSL routines:OPENSSL_internal:NO_CERTIFICATE_SET:/Library/Caches/com.apple.xbs/Sources/boringssl/ssl/tls13_server.cc:882: nw_endpoint_flow_failed_with_error [C3 fe80::1884:2662:90ca:b011%en0.65328 in_progress channel-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], scoped, ipv4, dns, uses wifi)] already failing, returning nw_endpoint_flow_failed_with_error [C4 192.168.0.98:65396 in_progress channel-flow (satisfied (Path is satisfied), viable, interface: en0[802.11], scoped, ipv4, dns, uses wifi)] already failing, returning quic_******_connection_state_handler [C1:1] [2ae0263d7dc186c7-] TLS error -9858 (state failed) nw_connection_copy_connected_local_endpoint_block_invoke [C3] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection nw_connection_copy_connected_remote_endpoint_block_invoke [C3] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C3] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection quic_******_connection_state_handler [C2:1] [84fdc1e910f59f0a-] TLS error -9858 (state failed) nw_connection_copy_connected_local_endpoint_block_invoke [C4] Client called nw_connection_copy_connected_local_endpoint on unconnected nw_connection nw_connection_copy_connected_remote_endpoint_block_invoke [C4] Client called nw_connection_copy_connected_remote_endpoint on unconnected nw_connection nw_connection_copy_protocol_metadata_internal_block_invoke [C4] Client called nw_connection_copy_protocol_metadata_internal on unconnected nw_connection Am I missing some configuration? I noticed with the working code that uses TCP and TLS that there is an NWParameters initializer that accepts tls options and tcp option but there isnt one that accepts tls and quic. Thank you for any help :)
19
0
1.5k
Dec ’24
peer-to-peer networking for iOS, iPadOS, watchOS, tvOS
Our product (rockhawk.ca) uses the Multipeer Connectivity framework for peer-to-peer communication between multiple iOS/iPadOS devices. My understanding is that MC framework communicates via three methods: 1) infrastructure wifi (i.e. multiple iOS/iPadOS devices are connected to the same wifi network), 2) peer-to-peer wifi, or 3) Bluetooth. In my experience, I don't believe I've seen MC use Bluetooth. With wifi turned off on the devices, and Bluetooth turned on, no connection is established. With wifi on and Bluetooth off, MC works and I presume either infrastructure wifi (if available) or peer-to-peer wifi are used. I'm trying to overcome two issues: Over time (since iOS 9.x), the radio transmit strength for MC over peer-to-peer wifi has decreased to the point that range is unacceptable for our use case. We need at least 150 feet range. We would like to extend this support to watchOS and the MC framework is not available. Regarding #1, I'd like to confirm that if infrastructure wifi is available, MC uses it. If infrastructure wifi is not available, MC uses peer-to-peer wifi. If this is true, then we can assure our customers that if infrastructure wifi is available at the venue, then with all devices connected to it, range will be adequate. If infrastructure wifi is not available at the venue, perhaps a mobile wifi router (battery operated) could be set up, devices connected to it, then range would be adequate. We are about to test this. Reasonable? Can we be assured that if infrastructure wifi is available, MC uses it? Regarding #2, given we are targeting minimum watchOS 7.0, would the available networking APIs and frameworks be adequate to implement our own equivalent of the MC framework so our app on iOS/iPadOS and watchOS devices could communicate? How much work? Where would I start? I'm new to implementing networking but experienced in using the MC framework. I'm assuming that I would write the networking code to use infrastructure wifi to achieve acceptable range. Many thanks! Tim
4
0
1.1k
Nov ’24
NWListener, P2P and awdl interfaces
I'm attempting to create a service that: Listens on iOS device A using NWListener Broadcasts the NWService ( using NWListener(service:using:)) ) on Bonjour Allows a separate device, iOS device B, to receive information about that service via an NWBrowser Connect to that service using the information contained in NWBrowser.Result 's NWEndpoint I've been able to successfully do this using a SwiftNIO service, in the following environments: iOS device A and iOS device B are physical iOS devices on the same WiFi network. This works. iOS device A and iOS device B are iOS simulators on the same machine. This works. iOS device A is a physical device, and iOS device B is a simulator. iOS device A is not connected to a WiFi network, iOS device B is connected to a WiFi network. This works. However, when iOS device A and iOS device B are physical devices that are not connected to a WiFi network, I encounter the following behavior: The Bonjour service is correctly advertised, and iOS device A and iOS device B are able to observe the advertisement of the service. In both cases, iOS device A and iOS device B, while able to resolve an NWEndpoint for the Bonjour service, are not able to connect to each other, and the connection attempt hangs. My setup for the listener side of things looks roughly like: let opts: NWParameters = .tcp opts.includePeerToPeer = true opts.allowLocalEndpointReuse = true let service = NWListener.Service(name: "aux", type: BONJOUR_SERVICE_TYPE, domain: "") try bootstrap.withNWListener(NWListener(service: service, using: opts)).wait() // bootstrap is an artifact of using SwiftNIO Similarly, my setup on the discovery side of things looks like: let params: NWParameters = .tcp params.includePeerToPeer = true let browser = NWBrowser(for: .bonjour(type: BONJOUR_SERVICE_TYPE, domain: BONJOUR_SERVICE_DOMAIN), using: params) browser.browseResultsChangedHandler =  { (searchResults, changed) in // save the result to pass on its NWEndpoint later } and finally, where I have an NWEndpoint, I use SwiftNIO's NIOTSConnectionBootstrap.connect(endpoint:) to initialize a connection to my TCP service ( a web socket server ). The fact that I am able to get P2P networking (presumably over an awdl interface?) between the simulator and the iOS device suggests to me that I haven't done anything obviously wrong in my setup. Similarly, the fact that it works over the same WiFi network and that, in P2P, I am able to at least observe the Bonjour advertisement, strikes me that I'm somewhere in the right neighborhood of getting this to work. I've also ensured that my Info.plist for the app has a NSLocalNetworkUsageDescription and NSBonjourServices for the Bonjour service type I'm browsing for. I've even attempted to exercise the "Local Network Permission" dialog by using a hacky attempt that sends data to a local IP in order to trigger a permissions dialog, though the hack does not appear to actually force the dialog to appear. Is there some trick or other piece of knowledge regarding allowing the use of P2P w/ Network.framework and TCP connections to services?
7
0
2.1k
Nov ’24
Network framework crashes from nw_browser_cancel call
Hi, I'm using the Network framework to browse for devices on the local network. Unfortunately, I get many crash reports that crash in nw_browser_cancel, of which two are attached. This discussion seems to have a similar issue, but it was never resolved: https://forums.developer.apple.com/forums/thread/696037 Contrary to the situation in the linked thread, my implementation uses DispatchQueue.main as the queue for the browser, so I don't think over-releasing the queue is the problem. I am unable to reproduce this problem myself, but one of my users can reproduce it reliably it seems. How can I resolve this crash? 2024-11-10_14-24-35.3886_+0100-4fdbdb8e944a4b655d60df53da3aa8c759f4fd1f.crash 2024-11-08_08-54-31.6366_+0100-303cabefb74bf89cdea3127b1cad122ee46016f2.crash
2
0
519
Nov ’24
Combining Bonjour and QUIC multiplex group using Network.framework
In my iOS app I am currently using Bonjour (via Network.framework) to have two local devices find each other and then establish a single bidirectional QUIC connection between them. I am now trying to transition from a single QUIC connection to a QUIC multiplex group (NWMultiplexGroup) with multiple QUIC streams sharing a single tunnel. However I am hitting an error when trying to establish the NWConnectionGroup tunnel to the endpoint discovered via Bonjour. I am using the same "_aircam._udp" Bonjour service name I used before (for the single connection) and am getting the following error: nw_group_descriptor_allows_endpoint Endpoint iPhone15Pro._aircam._udp.local. is of invalid type for multiplex group Does NWConnectionGroup not support connecting to Bonjour endpoints? Or do I need a different service name string? Or is there something else I could be doing wrong? If connecting to Bonjour endpoints isn't supported, I assume I'll have to work around this by first resolving the discovered endpoint using Quinn's code from this thread? And I guess I would then have to have two NWListeners, one just for Bonjour discovery and one listening on a port of my choice for the multiplex tunnel connection?
12
0
694
Nov ’24
Triggering the Local Network Privacy Alert
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 } }
0
0
8.6k
Nov ’24
Local Network Privacy FAQ
IMPORTANT This FAQ has been replaced by TN3179 Understanding local network privacy. I’m leaving this post in place as a historical curiosity, but please consult the technote going forward. I regularly get asked questions about local network privacy. This is my attempt to collect together the answers for the benefit of all. Before you delve into the details, familiarise yourself with the basics by watching WWDC 2020 Session 10110 Support local network privacy in your app. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Local Network Privacy FAQ With local network privacy, any app that wants to interact with devices on your network must ask for permission the first time that it attempts that access. Local network privacy is implemented on iOS, iPadOS, visionOS, and macOS. It’s not implemented on other platforms, most notably tvOS. IMPORTANT macOS 15 (currently in beta) introduced local network privacy support to the Mac. WWDC 2024 Session 10123 What’s new in privacy is the official announcement. This works much like it does on iOS, but there are some subtle differences. I’ll update this FAQ as I gain more experience with this change. Some common questions about local network privacy are: FAQ-1 What is a local network? FAQ-2 What operations require local network access? FAQ-3 What operations require the multicast entitlement? FAQ-4 Do I need the multicast entitlement? FAQ-5 I’ve been granted the multicast entitlement; how do I enable it? FAQ-6 Can App Clips access the local network? FAQ-7 How does local network privacy work with app extensions? FAQ-8 How do I explicitly trigger the local network privacy alert? FAQ-9 How do I tell whether I’ve been granted local network access? FAQ-10 How do I use the unsatisfied reason property? FAQ-11 Do I need a local network usage description property? FAQ-12 Can I test on the simulator? FAQ-13 Once my app has displayed the local network privacy alert, how can I reset its state so that it shows again? FAQ-14 How do I map my Multipeer Connectivity service type to an entry in the Bonjour services property? FAQ-15 My app presents the local network privacy alert unexpectedly. Is there a way to track down the cause? FAQ-16 On a small fraction of devices my app fails to present the local network privacy alert. What’s going on? FAQ-17 Why does local network privacy get confused when I install two variants of my app? FAQ-18 Can my app trigger the local network privacy alert when the device is on WWAN? Revision History 2024-10-31 Added a link to this FAQ’s replacement, TN3179 Understanding local network privacy. 2024-07-22 Added a callout explaining that local network privacy is now an issue on macOS. 2023-10-31 Fixed a bug in the top-level FAQ that mistakenly removed some recent changes. Added FAQ-18. 2023-10-19 Added a preamble to clarify that local network privacy is only relevant on specific platforms. 2023-09-14 Added FAQ-17. 2023-08-29 Added FAQ-16. 2023-03-13 Added connecting a UDP socket to FAQ-2. 2022-10-04 Added screen shots to FAQ-11. 2022-09-22 Fixed the pointer from FAQ-9 to FAQ-10. 2022-09-19 Updated FAQ-3 to cover iOS 16 changes. Made other minor editorial changes. 2020-11-12 Made a minor tweak to FAQ-9. 2020-10-17 Added FAQ-15. Added a second suggestion to FAQ-13. 2020-10-16 First posted.
0
0
24k
Oct ’24
Is is possible to grant Local Network permissions for a process through a Configuration Profile?
In the FAQ about Local Network, a lot of topics are covered but, unless I missed something, I didn't see the topic of MDMs being covered. [Q] Could the FAQ be updated to cover whether it is possible to grant this Local Network permission through a configuration profile? The answer, based on google searches and different forums, seems to be a negative. It seems a bit strange considering that this feature has been available on iOS for at least 3 years. Anyway, even if it is not possible, it would be useful to add in the FAQ that this is not possible.
1
0
509
Oct ’24
NWConnection is crashed on iOS 15 and 16, but it works well on 17
Hello 👋 I need to implement a logic for searching for devices with our own service type using Bonjour. Using the NWBrowser, I can receive a list of all devices and connect to them. I need to utilize a WebSocket connection. By the property endpoint of NWBrowser.Result objects I can create NWConnection. Below is my implementation which works fine on iOS 17: let params = NWParameters.tcp let webSocketOptions = NWProtocolWebSocket.Options() params.defaultProtocolStack.applicationProtocols.insert(webSocketOptions, at: 0) // The `endpoint` is from `browseResultsChangedHandler` of NWBrowser let connection = NWConnection(to: endpoint, using: params) However, it doesn't work on iOS 15 and 16 because of the crash: 2024-06-01 16:07:18.136068+0300 MyApp[591:16845549] [] nw_endpoint_get_url called with null endpoint 2024-06-01 16:07:18.136932+0300 MyApp[591:16845549] [] nw_endpoint_get_url called with null endpoint, dumping backtrace: [arm64] libnetcore-3100.102.1 0 Network 0x000000018530e174 __nw_create_backtrace_string + 188 1 Network 0x000000018538ba20 nw_endpoint_get_url + 852 2 Network 0x0000000185310020 nw_ws_create_client_request + 84 3 Network 0x0000000184f4b3cc __nw_ws_create_state_block_invoke + 416 4 Network 0x000000018504bc68 nw_protocol_options_access_handle + 92 5 Network 0x0000000184f41e98 nw_ws_create_state + 204 6 Network 0x0000000184f41aec __nw_protocol_copy_ws_definition_block_invoke_2 + 176 7 Network 0x0000000184f69188 nw_framer_protocol_connected + 348 8 Network 0x00000001854a6638 _ZL29nw_socket_handle_socket_eventP9nw_socket + 1560 9 libdispatch.dylib 0x0000000126b89d50 _dispatch_client_callout + 16 10 libdispatch.dylib 0x0000000126b8d208 _dispatch_continuation_pop + 756 11 libdispatch.dylib 0x0000000126ba48d4 _dispatch_source_invoke + 1676 12 libdispatch.dylib 0x0000000126b94398 _dispatch_workloop_invoke + 2428 13 libdispatch.dylib 0x0000000126ba0b74 _dispatch_workloop_worker_thread + 1716 14 libsystem_pthread.dylib 0x000000012371f814 _pthread_wqthread + 284 15 libsystem_pthread.dylib 0x000000012371e5d4 start_wqthread + 8 Also, there is the stack trace of bt-command in the debug console: * thread #20, queue = 'com.apple.network.connections', stop reason = EXC_BAD_ACCESS (code=1, address=0x0) * frame #0: 0x0000000123078c24 libsystem_platform.dylib`_platform_strlen + 4 frame #1: 0x00000001803c538c CoreFoundation`CFStringCreateWithCString + 40 frame #2: 0x0000000185310030 Network`nw_ws_create_client_request + 100 frame #3: 0x0000000184f4b3cc Network`__nw_ws_create_state_block_invoke + 416 frame #4: 0x000000018504bc68 Network`nw_protocol_options_access_handle + 92 frame #5: 0x0000000184f41e98 Network`nw_ws_create_state + 204 frame #6: 0x0000000184f41aec Network`__nw_protocol_copy_ws_definition_block_invoke_2 + 176 frame #7: 0x0000000184f69188 Network`nw_framer_protocol_connected + 348 frame #8: 0x00000001854a6638 Network`nw_socket_handle_socket_event(nw_socket*) + 1560 frame #9: 0x0000000126b89d50 libdispatch.dylib`_dispatch_client_callout + 16 frame #10: 0x0000000126b8d208 libdispatch.dylib`_dispatch_continuation_pop + 756 frame #11: 0x0000000126ba48d4 libdispatch.dylib`_dispatch_source_invoke + 1676 frame #12: 0x0000000126b94398 libdispatch.dylib`_dispatch_workloop_invoke + 2428 frame #13: 0x0000000126ba0b74 libdispatch.dylib`_dispatch_workloop_worker_thread + 1716 frame #14: 0x000000012371f814 libsystem_pthread.dylib`_pthread_wqthread + 284 I have found out a couple things: There are no crashes if I initialize the NWConnection object with using, for instance, the NWEndpoint.url(_:). initializer: let urlHost = URL(string: "ws://10.20.30.40:5060")! let endpoint = NWEndpoint.url(urlHost) let params = NWParameters.tcp let webSocketOptions = NWProtocolWebSocket.Options() params.defaultProtocolStack.applicationProtocols.insert(webSocketOptions, at: 0) let connection = NWConnection(to: endpoint, using: params) self.connection = connection But, in this case, I must extract IP-addresses 🙇‍♂️ Meanwhile, there is a topic such as Don’t Try to Get the Device’s IP Address.. I have tried to find anything that could help me move forward in this problem and run into some odd behaviour. There is a property skipHandshake of NWProtocolWebSocket.Options object. If I set the property value to true, there are no crashes as well as no connection to a device.
2
1
891
Oct ’24
UDP Receive is not working
Hello everyone I'm new to swift and I can't quite figure it out yet:( I am developing a simple online game for mac os that involves two players connected to the same WIFI. I need to constantly receive information from the server and I don't understand how to implement it. If I call the receive function indefinitely, then my program freezes. I realized that this should happen asynchronously, but that's just how my program understands when a package came from the server. I understand that I need a delegate or handler, but I don't understand how to do it. Please help me to add the receive function and everything that is necessary for it import Foundation import Network enum CustomErrors: Error { case DataError case NetworkError case DecoderError case InvalidAddress } class TapperConnection: ObservableObject { private var _serverAlive = false private var connection: NWConnection! private var serverPort: UInt16 = 20001 private var serverIp: String = "127.0.0.1" private var _myDeviceName = Host.current().localizedName ?? "" @Published var messageDc: [HostData] = [] @Published var messageLobby: [HostData] = [] @Published var messageState: GameData = GameData() private var buffer = 2048 private var _inputData = "" private var _outputData = "" private var _myIp = "" private var isServer = false private var isClient = false var myIp: String { return _myIp } var myDeviceName: String { return _myDeviceName } private func getMyIp() -&gt; String? { var address: String? var ifaddr: UnsafeMutablePointer&lt;ifaddrs&gt;? guard getifaddrs(&amp;ifaddr) == 0 else { return nil } guard let firstAddr = ifaddr else { return nil } for ifptr in sequence(first: firstAddr, next: { $0.pointee.ifa_next }) { let interface = ifptr.pointee let addrFamily = interface.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) { let name = String(cString: interface.ifa_name) if name == "en0" || name == "en2" || name == "en3" || name == "en4" || name == "pdp_ip0" || name == "pdp_ip1" || name == "pdp_ip2" || name == "pdp_ip3" { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(interface.ifa_addr, socklen_t(interface.ifa_addr.pointee.sa_len), &amp;hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) } } } freeifaddrs(ifaddr) return address } private func isValidIP(_ ip: String) -&gt; Bool { let regex = try! NSRegularExpression(pattern: "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") return regex.firstMatch(in: ip, range: NSRange(location: 0, length: ip.utf16.count)) != nil } @Sendable private func updateServerState(to state: NWConnection.State) { switch state { case .setup: _serverAlive = true case .waiting: _serverAlive = true case .ready: _serverAlive = true case .failed: _serverAlive = false case .cancelled: _serverAlive = false case .preparing: _serverAlive = false default: _serverAlive = false } } func createConnection() throws { let ip = getMyIp() if ip != nil { serverIp = ip! _myIp = ip! } else { throw CustomErrors.NetworkError } isServer = true do { try connectToServer() } catch { throw CustomErrors.NetworkError } } func createConnection(ip: String) throws { if isValidIP(ip) { serverIp = ip } else { throw CustomErrors.InvalidAddress } let _ip = getMyIp() if _ip != nil { _myIp = _ip! } else { throw CustomErrors.NetworkError } isClient = true do { try connectToServer() } catch { throw CustomErrors.NetworkError } } private func connectToServer() throws { if isServer { // ............... // run server exec // ............... } let _params = NWParameters(dtls: nil, udp: .init()) _params.requiredLocalEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host(_myIp), port: 20002) connection = NWConnection(host: NWEndpoint.Host(serverIp), port: NWEndpoint.Port(rawValue: serverPort)!, using: _params) connection.stateUpdateHandler = updateServerState(to:) connection.start(queue: .global()) while !_serverAlive {} do { try send(message: "im:\(_myDeviceName)") receive() } catch { print("Error sending disconnect message: \(error)") } } func closeConnection() { do { try send(message: "dc:\(_myDeviceName)") } catch { print("Error sending disconnect message: \(error)") } _serverAlive = false connection.cancel() } func send(message: String) throws { var error = false connection.send(content: message.data(using: String.Encoding.utf8), completion: NWConnection.SendCompletion.contentProcessed(({ NWError in if NWError == nil { print("Data was sent!") } else { error = true } }))) if error { throw CustomErrors.NetworkError } } func receive() { self.connection.receive(minimumIncompleteLength: 1, maximumLength: 65535) { data, _, isComplete, _ in if isComplete { if data != nil { let response: String = String(decoding: data!, as: UTF8.self) var decodeData: Any var messageType: MessageType (decodeData, messageType) = try! Decoder.decodeMessage(response) switch messageType { case MessageType.lobby: self.messageLobby = decodeData as! [HostData] case MessageType.state: self.messageState = decodeData as! GameData case MessageType.dc: self.messageDc = decodeData as! [HostData] } } self.receive() } } } }
1
0
480
Oct ’24
Detect nearby users on the same app
I am developing an application that allows you to interact with people on your local network. I have a view called ProfileView() which has has identifiers inside of it such as that build up the profile for each person. Essentially, what I want to do is discover people who are on this app on your local network, or who are nearby to you based on bluetooth. I do not want to use a server, as I would like this to be an application that does not require internet access to function. Also if possible, I would like a toggle to allow yourself to be discovered in the background, even if not using the app. Any ideas how to do this? Also, is there any better way to do this instead of Bluetooth and Local Network? Thank you Possible code chunks needed: Discover nearby bluetooth users Discover nearby network users Toggle for discovery Toggle for background discovery (while not using app) Share profile (mainly just text and a profile image)
2
0
705
Oct ’24