Network connections send and receive data using transport and security protocols.

Posts under Network tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Compatibility of Low-Level Socket APIs with Mapped IPv6 Addresses
I am currently working on an application that communicates with an IPv4 node in an IPv6-only network. During DNS resolution for the server node on JIO and T-Mobile networks, I am receiving IPv4 and mapped IPv6 addresses. In my application, I am using these mapped IPv6 addresses in two different contexts: For high-level API calls on the app side, I am using URLSession API (in either Objective-C or Swift). For another target(c/c++), I am making low-level socket API calls(bind etc). These calls use the address passed from the app layer. As node is resolved to IPV4 and mapped IPv6 addresses My question is: Are low-level Socket APIs(bind etc) compatible with these mapped IPv6 addresses (example 64:ff9b::103.135.122.10)? Mapped IPv6 with Well know perfix(64:ff9b) Please provide the document/rfc reference for the same. Any guidance or resources on this topic would be greatly appreciated.
3
1
351
Feb ’24
nw_protocol_error Crash on iOS 17.2 and later versions
Problem Description I've encountered a crash that only appears on iOS 17.2 and later versions (specifically iOS 17.2, iOS 17.2.1, and iOS 17.3). The crash started occurring after we switched our CDN to HTTP/3. Reverting the CDN back to a previous version eliminated the crash. The crash is of type EXC_BAD_ACCESS (SIGSEGV) with a KERN_INVALID_ADDRESS error. It was triggered in Thread 8, and the stack trace points to functions within the Network framework. I am unsure which part of my code is causing this issue when using HTTP/3. Any insights into what might be causing this crash or how to troubleshoot it would be greatly appreciated. Thank you. Steps to Reproduce It cannot be reproduced at present, but there are many crash logs in the crash report. Crash Report Triggered by Thread: 8 Kernel Triage: VM - (arg = ) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = ) mach_vm_allocate_kernel failed within call to vm_map_enter VM - (arg = ) mach_vm_allocate_kernel failed within call to vm_map_enter Thread 8 name: Thread 8 Crashed: 0 Network <memory_address> nw_protocol_error + 68 (protocol.cpp:577) 1 Network <memory_address> nw_channel_disconnect_flow(nw_channel*, nw_channel_input_flow*) + 172 (channel.cpp:2168) 2 Network <memory_address> invocation function for block in nw_channel_handle_defunct(nw_channel*) + 40 (channel.cpp:2928) 3 Network <memory_address> nw_hash_table_apply + 2696 (hash_table.cpp:454) 4 Network <memory_address> nw_channel_handle_defunct(nw_channel*) + 644 (channel.cpp:2926) 5 Network <memory_address> nw_channel_check_defunct(nw_channel*) + 92 (channel.cpp:2996) 6 Network <memory_address> nw_channel_remove_input_handler(nw_protocol*, nw_protocol*, bool) + 3332 (channel.cpp:661) 7 Network <memory_address> nw_protocol_ipv4_remove_input_handler(nw_protocol*, nw_protocol*, bool) + 148 (protocol_ip.cpp:639) 8 Network <memory_address> nw_protocol_udp_remove_input_handler(nw_protocol*, nw_protocol*, bool) + 156 (protocol_udp.cpp:271) 9 Network <memory_address> nw_protocol_implementation_teardown + 1028 (protocol_implementation.m:936) 10 Network <memory_address> nw_protocol_implementation_remove_input_handler + 2988 (protocol_implementation.m:0) 11 CFNetwork <memory_address> ConnectionProtocolRemoveInputHandler(nw_protocol*, nw_protocol*, bool) + 264 (ConnectionProtocol.cpp:102) 12 Network <memory_address> nw_endpoint_flow_failed_with_error(NWConcrete_nw_endpoint_handler*, bool, NSObject<OS_nw_error>*) + 536 (endpoint_flow.cpp:3449) 13 libdispatch.dylib <memory_address> _dispatch_call_block_and_release + 32 (init.c:1530) 14 libdispatch.dylib <memory_address> _dispatch_client_callout + 20 (object.m:561) 15 libdispatch.dylib <memory_address> _dispatch_workloop_invoke + 2152 (queue.c:4485) 16 libdispatch.dylib <memory_address> _dispatch_root_queue_drain_deferred_wlh + 288 (queue.c:6913) 17 libdispatch.dylib <memory_address> _dispatch_workloop_worker_thread + 404 (queue.c:6507) 18 libsystem_pthread.dylib <memory_address> _pthread_wqthread + 288 (pthread.c:2629) 19 libsystem_pthread.dylib <memory_address> start_wqthread + 8 (:-1)
3
0
507
Jan ’24
How to install dualpi2 qdisc on the rpi (router) to simulate congestion to test L4S
https://github.com/L4STeam/linux/ I tried installing the qdisc dualpi2 from the above link following the steps given in the Readme file onto the Raspberry pi 4 B At first I get the error: Couldn't find DTB bcm2711-rpi-4-b.dtb on the following paths: /etc/flash-kernel/dtbs /usr/lib/linux-image-5.15.72+ /lib/firmware/5.15.72+/device-tree/ I copied the file generated in the arch folder to the following locations, and run make modules_install make install For make install, i get "out of memory" error I tried following the steps mentioned below cd ~ mkdir initramfs cd initramfs sudo cp -a /boot . cd boot sudo update-initramfs -ut -b . sudo cp -a * /boot sudo apt-get autoremove Step 6 gives out of memory error. How do I fix the same?
0
0
234
Jan ’24
Is the code in 'Building a custom peer-to-peer protocol' insecure?
I'm new to Networking, so forgive me if this is a silly question: In the sample code, Building a custom peer-to-peer protocol, TLS is configured as follows: // Create TLS options using a passcode to derive a pre-shared key. private static func tlsOptions(passcode: String) -> NWProtocolTLS.Options { let tlsOptions = NWProtocolTLS.Options() let authenticationKey = SymmetricKey(data: passcode.data(using: .utf8)!) var authenticationCode = HMAC<SHA256>.authenticationCode(for: "TicTacToe".data(using: .utf8)!, using: authenticationKey) let authenticationDispatchData = withUnsafeBytes(of: &authenticationCode) { (ptr: UnsafeRawBufferPointer) in DispatchData(bytes: ptr) } sec_protocol_options_add_pre_shared_key(tlsOptions.securityProtocolOptions, authenticationDispatchData as __DispatchData, stringToDispatchData("TicTacToe")! as __DispatchData) sec_protocol_options_append_tls_ciphersuite(tlsOptions.securityProtocolOptions, tls_ciphersuite_t(rawValue: TLS_PSK_WITH_AES_128_GCM_SHA256)!) return tlsOptions } The sample code touts the connection as secure ("...uses Bonjour and TLS to establish secure connections between nearby devices"), but to my untrained eye it doesn't seem so. My reasoning is as follows: If I adapt this code as-is, so connections between two instances of my app use SymmetricKeys derived from the four-digit passcode, then wouldn't my encryption be easy to break by an adversary who sends 0000...9999 and records corresponding changes in the encryption, exposing my app to all sorts of attacks? The sample uses the passcode to validate the connection (host user shows client user the passcode, which is manually entered), which is a feature I would like to keep in some form or another, which is why this is causing so many headaches. Generally speaking, is there a way to secure a local peer-to-peer connection over Network.framework that doesn't involve certificates? If certificates are the only way, are there good resources you can recommend?
6
0
730
May ’24
PusherSwift Can't establish a websocket connection
I'm trying to connect to a socket from my own application, when I call pusher.connect() the following is displayed in the console: 2024-01-23 13:05:30.963189+0500 pusher_test[64299:2525981] [] nw_protocol_copy_ws_definition_block_invoke [C1:1] nw_ws_validate_server_response 2024-01-23 13:05:30.964076+0500 pusher_test[64299:2525981] [connection] nw_read_request_report [C1] Receive failed with error "Software caused connection abort" Below is my code for testing class AuthRequestBuilder: AuthRequestBuilderProtocol { func requestFor(socketID: String, channelName: String) -&gt; URLRequest? { var request = URLRequest(url: URL(string: authPath)!) request.httpMethod = "POST" request.addValue("Bearer "+token, forHTTPHeaderField: "Authorization") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") return request } } let optionsWithEndpoint = PusherClientOptions( authMethod: AuthMethod.authRequestBuilder(authRequestBuilder: AuthRequestBuilder()), host:.host(host), port:6001, useTLS: false ) pusher = Pusher(key: "pusher_app_key", options: optionsWithEndpoint) pusher.connect() let myPresenceChannel = pusher.subscribeToPresenceChannel(channelName: "presence-online") I write in flutter and am new to swift, but the error occurs in native, that's why I'm here. xcode version: 14.3.1. Swift version: swift-driver version: 1.75.2 Apple Swift version 5.8.1 (swiftlang-5.8.0.124.5 clang-1403.0.22.11.100) I tested it on the iOS simulator, but the error persists on a real device
1
0
280
Jan ’24
Behavior of URLSession with http3RelayEndpoint Proxy config
Hi, I am implementing the HTTP3 Relay server, and testing by the URLSession, let relayEndpoint = NWEndpoint.url(URL(string:"https://localhost:8002")!) let relayServer = ProxyConfiguration.RelayHop( http3RelayEndpoint: relayEndpoint, additionalHTTPHeaderFields: ["Proxy-Authorization":"Basic ***"] ) let relayConfig = ProxyConfiguration(relayHops: [relayServer]) let config = URLSessionConfiguration.default config.proxyConfigurations = [relayConfig] let s = URLSession(configuration: config) I have implemented both the CONNECT method and CONNECT method with :protocol of CONNECT-UDP over HTTP/3. If I enabled CONNECT-UDP only, when I try to connect some HTTP/3 URL like https://quic.aiortc.org/4, it works without problem. And URLSession will use the CONNECT-UDP to connect the UDP channel, throw which the URLSession will do the HTTP/3 request. However, if i enabled both the CONNECT-UDP and CONNECT (for TCP tunnel), the URLSession seems wired. It first try to establish the tunnel for UDP using the CONNECT-UDP method, and then closed it. And finally, it created the TCP tunnel using the CONNECT method. So is there any detailed document for the behavior of the behavior of URLSession with http3RelayEndpoint? Thanks you.
0
0
399
Jan ’24
NWConnectionGroup stateUpdateHandler not called for failed states
I'm building a network client with Swift (using QUIC). I set everything up properly (I know this because I can successfully connect, send and receive streams). But I'm trying to catch connection errors. For example if I try to connect to a totally bogus IP address, I would like to display Connecting, then ConnectionFailed I do the following: create my NWMultiplexGroup descriptor set my appropriate NWParameters create my NWConnectionGroup set up my handlers (setReceiveHandler, newConnectionHandler) and my state update handler i call connection.start When I pass a valid address to a server that is listening for the connection, all is good - in my stateUpdateHandler I get the .ready state, but I don't get any intermediate states, and if I pass it a bogus IP address, I get absolutely no callbacks to my handler (I would have expected to get .waiting and/or .failed) I couldn't find any quic options that I'm not doing, and the apple documentation is not helpful Any suggestions as to what I might be missing?
0
0
494
Jan ’24
App Sandbox - Outgoing connections
To restrict outgoing connections, I've ensured that the following key in not present in the entitlement file: <key>com.apple.security.network.client</key> <true/> The api calls made using URLSession and WKWebView are restricted as expected, but the same is not the case with MKMapView. The map content and the directions api are able to make outgoing network calls. Please let me know if it's possible to reliably restrict outgoing network connections in a sandboxed app?
8
0
904
Jan ’24
WiFi Networking when app is developed Godot - C# - VSCode - Xcode
I'm developing a 'game' using the Godot game framework. The 'game' will run on an IOS device and connect to an app that is running on my computer. The app I am connecting to communicates via UDP. When I run the app in Godot's simulator using either the loopback address 127.0.0.1 or the WiFi address of the computer it works fine. I am attempting to send a Unicast UDPpacket from the IOS device to the computer. The UDPpacket is never sent from the IOS device as verified by Wireshark and also the network tab on xcode as the 'game' is debugged via Xcode. The first time the app is sent to the iphone during the debug session from Xcode, a message on the iPhone pops up "MyAppName" would like to find and connect to devices on your local network. (I clicked on "Allow") When the app is debugged on the iphone via Xcode, debug message from near the point where UDPPackets are sent are displayed in the debugger. After about 5 seconds an error is thrown from the UDPClient "No route from host..." There is a loop to send UDPpackets is again if the expected response is not received from the app, the "No route from host" again is shown in 5 seconds. Settings: Ip address on computer and iphone are within the same network (do not need to be routed) Firewall is off on the computer during testing iPhone Settings (MyAppName is not shown anywhere in settings) Godot 4.2.1, .Net 8.0.101, XCode 15.2, VSCode 1.85.2 **Godot editor -> Project -> Exports -> Presets -> IOS (Runnable) ** [Options Tab] Access WiFi [x] is checked Provisioning Profile UUID for both Debug and Release is BLANK [Resources Tab] {All fields are blank} [Features Tab] Feature list = arm64, astc, etc2, ios, mobile [Encryption Tab] {everything is off or blank} I suspect that I'm not using entitlements properly. I have been granted the multicast entitlement, but I'm not certain how to implement it in my Godot -> VSCode ->Xcode workflow.
2
0
426
Jan ’24
Weird behaviour with Network Framework and QUIC Multiplex Groups.
Hey all here is an example you can try out: https://github.com/paxsonsa/quic-swift-demo I am prototype a QUIC base application system with a client and server. My server is a simple test to experiment with QUIC and Network Framework but I am see some odd behaviour. Selecting Stream Direction for new streams In the example below, we are creating a new multiplexed QUIC connection and establish a new stream once the group connection is ready. In some cases, I want to be able to use a different stream kind (uni/bi). By specifying the options, I get an error in Xcode console like so: running.... group state: waiting(POSIXErrorCode(rawValue: 50): Network is down) group state: ready Connected using QUIC! nw_endpoint_flow_setup_cloned_protocols [C3 127.0.0.1:4567 in_progress socket-flow (satisfied (Path is satisfied), viable, interface: lo0)] could not find protocol to join in existing protocol stack nw_endpoint_flow_failed_with_error [C3 127.0.0.1:4567 in_progress socket-flow (satisfied (Path is satisfied), viable, interface: lo0)] failed to clone from flow, moving directly to failed state Main Connection State: failed(POSIXErrorCode(rawValue: 50): Network is down) quic_recovery_pto PTO fired after validation Here is my swift code: // // main.swift // QuicTool // // Created by Andrew Paxson on 2024-01-14. // import Foundation import Network /// Helper function to create a message frame. func createMessage(version: UInt8, messageType: UInt8, message: String) -> Data { let messageData = message.data(using: .utf8) ?? Data() let length = UInt32(messageData.count) var data = Data() data.append(version) data.append(messageType) // Convert length to 4 bytes and append (big-endian format) let bigEndianLength = length.bigEndian data.append(contentsOf: withUnsafeBytes(of: bigEndianLength) { Array($0) }) // Append 2 bytes of padding for 8-byte alignment data.append(Data(repeating: 0, count: 2)) // Add Message Data. data.append(messageData) return data } // Queue for QUIC things. let queue = DispatchQueue(label: "quic", qos: .userInteractive) // Create Inital Options for the tunnel. // This is using an insecure connection as this operation is meant to be local network. let endpoint = NWEndpoint.hostPort(host: "127.0.0.1", port: .init(integerLiteral: 4567)) let options = NWProtocolQUIC.Options(alpn: ["demo"]) // Set the initial stream to bidirectional. options.direction = .bidirectional sec_protocol_options_set_verify_block(options.securityProtocolOptions, { (sec_protocol_metadata, sec_trust, sec_protocol_verify_complete) in sec_protocol_verify_complete(true) }, queue) let parameters = NWParameters(quic: options) // 1) Create a new multiplexed connection let descriptor = NWMultiplexGroup(to: endpoint) let group = NWConnectionGroup(with: descriptor, using: parameters) var mainConn: NWConnection? = nil // Here we are establishing a state handler for when the connection to the // the server is neogiated and "ready". Once its ready we want to establish a // stream using the group with the options set. // // This is the main location of the issue we are seeing where the stream is // established and the data is sent but never updated. group.stateUpdateHandler = { newState in print("group state: \(newState)") switch newState { // Once the tunnel is established, create a new stream with bidirectional parameters. case .ready: print("Connected using QUIC!") // 2) In normal application I may want to open different kinds of streams in providing // new options. Is there a better way to select the stream kind for subsequent streams? let options = NWProtocolQUIC.Options(alpn: ["demo"]) options.direction = .bidirectional // When providing unique options the stream will fail. Removeing the using argument works. mainConn = group.extract()! // force unwrap mainConn?.stateUpdateHandler = { state in print("Main Connection State: \(state)") switch state { case .ready: // Once the connection is ready, lets send some sweet data sauce. // // By establishing this new stream and sending data, on the server this causes the inital // stream with no handle to be open. let version: UInt8 = 1 let messageType: UInt8 = 1 let message = "hello, I am from the multiplex group ready." let messageData = createMessage(version: version, messageType: messageType, message: message) mainConn?.send(content: messageData, isComplete: true, completion: .contentProcessed({ sendError in if let error = sendError { print("There was an error sending data: \(error)") } else { print("Data was sent successfully from Main Connection.") } })) default: break } } // Don't forget to start the connection. mainConn?.start(queue: queue) default: break } } // Receive new incoming streams initiated by the remote endpoint // this is not used for this example. group.newConnectionHandler = { conn in print("New Connection: \(conn)") // Set state update handler on incoming stream conn.stateUpdateHandler = { newState in print("newState: \(newState) for \(conn)") switch newState { case .ready: print("got a new stream!") default: break } } // Start the incoming stream conn.start(queue: queue) } // Start the group with callback queue group.start(queue: queue) print("running....") // We iterate trying to send data on the new stream we created after the // connection is established. while true { switch mainConn?.state { case .ready: // Once the connection is ready, lets send some sweet data sauce. let version: UInt8 = 1 let messageType: UInt8 = 1 let message = "hello, im from the main loop" let messageData = createMessage(version: version, messageType: messageType, message: message) print("Local Stream Send: \(messageData)") mainConn?.send(content: messageData, completion: .contentProcessed({ sendError in if let error = sendError { print("There was an error sending data: \(error)") } })) sleep(1) default: continue } }
8
0
948
Jan ’24
Wired data transfer between an app on two iOS/iPadOS devices--Possible or pipe dream?
If two iOS/iPadOS devices have your app opened, is it possible to have the apps send data to each other over a wired connection? E.g. If two iPhone 15s are connected by USB-C, can I get my app in iPhone A to send data to iPhone B and vice-versa? I've been looking around for quite a while now and at this point I just want to know if it's technically feasible.
5
0
810
Feb ’24
Using CUPS in iOS
I want to use CUPS in iOS for printing and it is mentioned at many places that we can use cups for printing in ios .But when i import library cups/cups.h ,xcode is giving error "cups/cups.h not found". code i am using in a objective c file : import &amp;lt;cups/cups.h&amp;gt; cups_dest_t *dest; int num_options; cups_option_t *options; int job_id; /* Print a single file */ job_id = cupsPrintFile(dest-&amp;gt;name, "/usr/share/cups/data/testprint.ps", "Test Print", num_options, options); Do i need to intall some driver or any library to make it work ? or is it the case that CUPS is not available for iOS?
3
0
1.1k
Jan ’24
Network.framework crash on iOS 12: symbol not found _$s7Network12NWConnectionC5StateOMa
I'm building an older app that's on the app store in XCode 15.2. It runs fine on iOS 15, 16, 17. It is supported on iOS 12 and when I try to run on iOS 12 it crashes. I'm not sure why this is happening. Anyone know? Crash report: Photobooth-2024-01-11-181720.ips Snippet: Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Termination Description: DYLD, Symbol not found: _$s7Network12NWConnectionC5StateOMa | Referenced from: /private/var/containers/Bundle/Application/C5B7AB67-6F8C-4EE3-977C-2076C4F06729/Photobooth.app/Frameworks/VideoNetworkFramework.framework/VideoNetworkFramework | Expected in: /System/Library/Frameworks/Network.framework/Network Triggered by Thread: 0
2
0
790
Jan ’24
Unable to detect TLS PSK Failure in Bonjour "Service" mode for NWConnection/NWListener
Hi there, we're looking to build a Bonjour service for our users so that they can share data between devices. Things are mostly going ok, but we would like to make sure the connection is secure. Being good developers we took a look at the TicTacToe example from WWDC. This looks great! We'd love to secure our comms with the latest TLS via a Pre Shared Key (PSK) e.g. a Passcode in our case. In the normal happy path, things work well, we can send and receive messages and all is well. However, when we enter the wrong passcode we don't receive any notification back on the client side. The server can detect the incorrect passcode, but the client is left hanging around. The issue only appears to affect a Bonjour service or mode (not quite sure of the terminology here). If we explicitly specify a host (e.g. "localhost" and port (e.g. 12345) for connection/listening then we get the expected callbacks on both client/server that the PIN was incorrect. However if we just setup a service and try to connect to it (in our case we use NWBrowser in our App, but below we create an endpoint manually), everything works fine for a good passcode, but for a bad passcode we don't receive any callback and have no way to know the passcode was no good and inform the user. So, we'd love to be able to detect that incorrect passcode on the client side. What are we doing wrong. Sample code below (mostly shamelessly ripped from some of @eskimos sample code in another issue) demonstrates the issue, change the ServiceMode / Passcodes inside main() to see the issue. Hoping we can page Dr. @eskimo and Dr. @meaton - Could really do with your expertise here. Ta! import CryptoKit import Foundation import Network let ServerName = "My-Bonjour-Server" let ServiceName = "_my_bonjour_service._tcp" var listenerRef: NWListener? var receiveConnectionRef: NWConnection? var sendConnectionRef: NWConnection? enum ServiceMode { case explicitHostAndPort // This works all the time case bonjourService // This doesn't work for an incorrect passcode } extension NWParameters { // Just ripped from the TicTacToe example convenience init(passcode: String) { self.init(tls: NWParameters.tlsOptions(passcode: passcode)) } 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: ServiceName.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(ServiceName)! as __DispatchData) sec_protocol_options_append_tls_ciphersuite(tlsOptions.securityProtocolOptions, tls_ciphersuite_t(rawValue: TLS_PSK_WITH_AES_128_GCM_SHA256)!) return tlsOptions } 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 } } func startListener(passcode: String, serviceMode: ServiceMode) { let listener: NWListener switch serviceMode { case .explicitHostAndPort: listener = try! NWListener(using: NWParameters(passcode: passcode), on: 12345) case .bonjourService: listener = try! NWListener(using: NWParameters(passcode: passcode)) listener.service = NWListener.Service(name: ServerName, type: ServiceName) } listenerRef = listener listener.stateUpdateHandler = { state in print("listener: state did change, new: \(state)") } listener.newConnectionHandler = { conn in if let old = receiveConnectionRef { print("listener: will cancel old connection") old.cancel() receiveConnectionRef = nil } receiveConnectionRef = conn startReceive(on: conn) conn.start(queue: .main) } listener.start(queue: .main) } func startReceive(on connection: NWConnection) { connection.receive(minimumIncompleteLength: 1, maximumLength: 2048) { dataQ, _, _, errorQ in if let data = dataQ, let str = String(data: data, encoding: .utf8) { print("receiver: did receive: \"\(str)\"") } if let error = errorQ { if case let .tls(oSStatus) = error, oSStatus == errSSLBadRecordMac { print("receiver has detected an Incorrect PIN") } else { print("receiver: did fail, error: \(error)") } return } } } func startSender(passcode: String, serviceMode: ServiceMode) { let connection: NWConnection switch serviceMode { case .explicitHostAndPort: connection = NWConnection(host: "localhost", port: 12345, using: NWParameters(passcode: passcode)) case .bonjourService: let endpoint = NWEndpoint.service(name: ServerName, type: ServiceName, domain: "local.", interface: nil) connection = NWConnection(to: endpoint, using: NWParameters(passcode: passcode)) } sendConnectionRef = connection connection.stateUpdateHandler = { state in if case let .waiting(error) = state { if case let .tls(os) = error, os == errSSLPeerBadRecordMac { // Incorrect PIN print("Sender has detected an Incorrect PIN") } } else { print("sender: state did change, new: \(state)") } } connection.send(content: "It goes to 11".data(using: .utf8), completion: .idempotent) connection.start(queue: .main) } func main() { let serviceMode: ServiceMode = .explicitHostAndPort // Set this to Bonjour to see the issue // Change one of the Passcodes below to see the incorrect pin message(s) or lack thereof startListener(passcode: "1234", serviceMode: serviceMode) // Wait for server to spin up... DispatchQueue.main.asyncAfter(deadline: .now() + 1) { startSender(passcode: "1234", serviceMode: serviceMode) } dispatchMain() } main() exit(EXIT_SUCCESS)
4
0
484
Jan ’24
Unhandled Exception: SocketException: Failed to create datagram socket (OS Error: Can't assign requested address, errno = 49), address = 255.255.255.255, port = 1050
I am using RawDatagramSocket.bind(InternetAddress('255.255.255.255'), 1050) in Flutter also added local network access permission with a description but still getting this error Unhandled Exception: SocketException: Failed to create datagram socket (OS Error: Can't assign requested address, errno = 49), address = 255.255.255.255, port = 1050
1
0
429
Jan ’24
Stealth Mode broken in Sleep
Hello here, There is a macOS feature called Stealth Mode under Firewall in System Settings. It's supposedly blocks ICMP request messages (aka Ping). It seems to work fine, only until the device is put to sleep. This can be done either manually from Apple Menu -> Sleep, or by simply closing the MacBook lid. The device suddenly starts replying to pings roughly 10 seconds after entering sleep mode. Exactly the same seems to happen even if I enable pf with a rule: block all Does anyone know what's happening? Seems like packet filtering or firewall is not applied anymore after the OS is put to sleep. Are the ICMP packets handled by the Kernel or WNIC firmware after sleep? I reported this through Apple Feedback Assistant but they were very dismissive and simply said they were not able to reproduce this.
0
0
279
Jan ’24
How to implement ping an IP in MacOS Swift?
Hi all, As far as my research, I found there are two ways to ping an IP Address (ipv4 and ipv6) in MacOS in Swift. SimplePing Run command line in code like below func doPing() { let task = Process() task.executableURL = URL(fileURLWithPath: "/sbin/ping") task.arguments = [ "-c", "4", "10.1.141.100" ] let outputPipe = Pipe() task.standardOutput = outputPipe let outputHandle = outputPipe.fileHandleForReading outputHandle.readabilityHandler = { pipe in if let ouput = String(data: pipe.availableData, encoding: .utf8) { if !ouput.isEmpty { log += ouput print("----> ouput: \(ouput)") } } else { print("Error decoding data: \(pipe.availableData)") } } task.launch() } So which way is better and which way should I implement for the project?
3
0
459
Jan ’24
Notification Service Extension usage time
Hello all. I noticed, that NSE living more than 30 seconds ( that described in doc ). When app receive notification, it created process NSE, and send notification to didReceive function, after this, app have 30 seconds to call contentHandler closure, after contentHandler is called, I expected that NSE process is killed, but it's not. If app using singletons in NSE, they won't dealloc after contentHandler is called, so, after new notification received, singletons still alive. Does it legal to not drop connection to websocket after contentHandler closure get called? For example, notification received, NSE process is loaded, websocket manager signleton is initialzied and started session, after few seconds contentHandler closure get called, so, system won't kill NSE because of 30 seconds timer, and my web socket connection will alive so long as possible, so, I not need to open it each 30 seconds, is that legal or not?)
3
0
530
Jan ’24
NWConnection, how to catch error?
I have a NWConnection, that if an invalid (ip/port), is entered, I get in debug the error: nw_socket_handle_socket_event [C1.1.1:1] Socket SO_ERROR 61. But I can't seem to trap that error. I have as my stateChangeHandler: I am creating my connection: let tcpOptions = NWProtocolTCP.Options() tcpOptions.enableKeepalive = true tcpOptions.keepaliveIdle = 2 tcpOptions.keepaliveCount = 2 tcpOptions.keepaliveInterval = 2 let params = NWParameters(tls: nil, tcp: tcpOptions) nwConnection:NWConnection(host: NWEndpoint.Host(host), port: NWEndpoint.Port(port)!, using: params). (with known nonexistent ip/port). I was hopping when I did a .start(), I would get an error in my state handler: // =============================================================================== func stateDidChange(to state: NWConnection.State) { Swift.print("State change") switch state { case .waiting(let error): print("Client waiting") connectionDidFail(error: error) case .ready: print("Client connection ready") case .failed(let error): print("Client failed") connectionDidFail(error: error) case .preparing: print("client preparing") case .setup: print("client setup") case .cancelled: print("client cancelled") default: print("Client unknown") break } } But it doesn't trap an error. So, where is this error coming from (I know the cause), but I want to trap it (in case a user puts in a wrong ip/port)
4
0
718
Jan ’24