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

Posts under Network tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Networking Resources
General: 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 DevForums 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 Adapt to changing network conditions tech talk Foundation networking: DevForums tags: Foundation, CFNetwork URL Loading System documentation — NSURLSession, or URLSession in Swift, is the recommended API for HTTP[S] on Apple platforms. Network framework: DevForums tag: Network Network framework documentation — Network framework is the recommended API for TCP, UDP, and QUIC on Apple platforms. Network Extension (including Wi-Fi on iOS): See Network Extension Resources Wi-Fi Fundamentals Wi-Fi on macOS: DevForums tag: Core WLAN Core WLAN framework documentation Wi-Fi Fundamentals Secure networking: DevForums 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 Technote 2232 HTTPS Server Trust Evaluation Technote 2326 Creating Certificates for TLS Testing QA1948 HTTPS and Test Servers Miscellaneous: More network-related DevForums tags: 5G, QUIC, Bonjour On FTP DevForums post Using the Multicast Networking Additional Capability DevForums post Investigating Network Latency Problems DevForums post Local Network Privacy FAQ DevForums post Extra-ordinary Networking DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com"
0
0
2.5k
Feb ’24
Custom DNS for specific domains
Hello, I have a company laptop thats connected to the internet without a VPN. I need to be able to resolve my company's sub domains using a specific dns server, and have all other domains resolved by the system wide name server. In windows, this is trivial to do. In an admin powershell I run "Add-DnsClientNrptRule -Namespace ".foo.mycompany.com" -Nameserver "127.0.0.1" and resolution requests for *.foo.mycompany.com is sent to a name server running on the localhost. All other dns resolution requests are handled by the system configured resolver. MacOS does have the /etc/resolver/ solution for this, but my understanding from these forums is that this is not the recommended approach. Note - I have tried it and it works. AFAIU, the recommended approach is to create a system Network extension using NEDNSProxyProvider, override handleNewFlow() and do what's necessary. The issue with this solution is that it requires handling all the dns flow parsing of DNS datagrams to extract the host forwarding the datagrams to the appropriate dns server Handle responses. Deal with flow control Handle edge cases. I was hoping for something much simpler than us needing to implement datagram parsing. Could you please shed light on our options and how we could proceed ?
0
0
31
2h
Local Network Access can't check in iOS18.0
In the past, I used to ping my iPhone‘s local IP address via UDP. If local network permissions were not enabled, it would return an error. If they were enabled, it would return success, which I used to determine whether my app had local network permissions enabled. Now, with iOS 18, it seems to not work anymore. Regardless of whether local network permissions are enabled, pinging the iPhone‘s local IP address always returns success. Is there any other good method to check this permission status? Case-ID: 9934335
0
0
37
9h
iOS Socket cannot connect ipv6 address when use PacketTunnelProvider
I'm use iPad OS 17.5.1, when I try to use socket to connect to an ipv6 address created by PacketTunnelProvider in my iOS device, an error occurs. Here is the code to create socket server and client: #include <stdio.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> int dx_create_ipv6_server(const char *ipv6_address, int port) { int server_fd; struct sockaddr_in6 server_addr; server_fd = socket(AF_INET6, SOCK_STREAM, 0); if (server_fd == -1) { perror("socket() failed"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); if (inet_pton(AF_INET6, ipv6_address, &server_addr.sin6_addr) <= 0) { perror("inet_pton() failed"); close(server_fd); return -1; } if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind() failed"); close(server_fd); return -1; } if (listen(server_fd, 5) == -1) { perror("listen() failed"); close(server_fd); return -1; } printf("Server is listening on [%s]:%d\n", ipv6_address, port); return server_fd; } int dx_accept_client_connection(int server_fd) { int client_fd; struct sockaddr_in6 client_addr; socklen_t client_addr_len = sizeof(client_addr); client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len); if (client_fd == -1) { perror("accept() failed"); return -1; } char client_ip[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, &client_addr.sin6_addr, client_ip, sizeof(client_ip)); printf("Client connected: [%s]\n", client_ip); return client_fd; } int dx_connect_to_ipv6_server(const char *ipv6_address, int port) { int client_fd; struct sockaddr_in6 server_addr; client_fd = socket(AF_INET6, SOCK_STREAM, 0); if (client_fd == -1) { perror("socket() failed"); return -1; } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); if (inet_pton(AF_INET6, ipv6_address, &server_addr.sin6_addr) <= 0) { perror("inet_pton() failed"); close(client_fd); return -1; } if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("connect() failed"); close(client_fd); return -1; } printf("Connected to server [%s]:%d\n", ipv6_address, port); close(client_fd); return 0; } @implementation SocketTest + (void)startSever:(NSString *)addr port:(int)port { [[NSOperationQueue new] addOperationWithBlock:^{ int server_fd = dx_create_ipv6_server(addr.UTF8String, port); if (server_fd == -1) { return; } int client_fd = dx_accept_client_connection(server_fd); if (client_fd == -1) { close(server_fd); return; } close(client_fd); close(server_fd); }]; } + (void)clientConnect:(NSString *)addr port:(int)port{ [[NSOperationQueue new] addOperationWithBlock:^{ dx_connect_to_ipv6_server(addr.UTF8String, port); }]; } @end PacketTunnelProvider code: override func startTunnel(options: [String : NSObject]?, completionHandler: @escaping (Error?) -> Void) { let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: "fd84:306d:fc4e::1") let ipv6 = NEIPv6Settings(addresses: ["fd84:306d:fc4e::1"], networkPrefixLengths: 64) settings.ipv6Settings = ipv6 setTunnelNetworkSettings(settings) { error in if error == nil { self.readPackets() } completionHandler(error) } } private func readPackets() { // do nothing packetFlow.readPackets { [self] packets, protocols in self.packetFlow.writePackets(packets, withProtocols: protocols) self.readPackets() } } At main target, in viewcontroller's viewDidAppear, after starting the VPN, executed following code: [SocketTest startSever:@"fd84:306d:fc4e::1" port:12345]; sleep(3); [SocketTest clientConnect:@"fd84:306d:fc4e::1" port:12345]; The startSever is executed correctly, but when executing: connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) in clientConnect, the code is blocked until it times out and returns -1. **Even if I use GCDAsyncSocket or BlueSocket, I get the same error. The strange thing is that if I use the ipv4 address in PacketTunnelProvider, and change the above code to the ipv4 version and connect to ipv4 address, or use GCDAsyncSocket to perform the corresponding operation, it can be executed correctly. ** I tried to search Google for problems with ios-related ipv6 addresses, but I still couldn't find a solution. Is this a bug in the ios system or is there something wrong with my code? I hope to get your help! Stackoverflow url: iOS Socket cannot connect ipv6 address when use PacketTunnelProvider
1
0
26
10h
Get DNS servers from the system
Hello! I'd like to ask about the best way of getting a list of DNS servers from the system (iOS & macOS). Why? I am using NEPacketTunnelProvider to implement a VPN app. When a device joins a network with a Captive Portal and the VPN is on, the VPN should redirect DNS queries to the DNS servers that were received from the network's DHCP server. So that my VPN is able to correctly reroute the traffic which is not blocked by the network's gateway and the Captive Portal landing page is served. When I don't do anything, the traffic goes to the tunnel and the tunnel's encrypted traffic is then dropped by the gateway serving the Captive Portal. When I temporarily turn off the VPN, opt out of all the traffic or pass the traffic to the system resolver, the traffic gets affected by other network settings (like DNSSettings) which leads to the same situation - the user not being able to authenticate with the Captive Portal. So far, I have tried multiple ways, including res_9_getservers but unsuccessfully. As a part of my investigation, I have found out that the /etc/resolv.conf file is not populated with DNS servers until the Captive Portal is acknowledged by the user which makes getaddrinfo unusable to achieve my goal. But I am not sure if that's a bug or intended behavior. Thank you for your help!
2
0
53
12h
Issue with Wi-Fi Connection on iOS 18.0 iPhone 16 Series
Dear Apple Support Team, I hope this message finds you well. I am writing to report an issue I have encountered with Wi-Fi connectivity on my iPhone 16 series running iOS 18.0. The problem occurs as follows: When attempting to connect my iPhone 16 series (iOS 18.0) to a Wi-Fi network, the connection always fails. After this failed attempt, any other iPhone (not from the 16 series) running iOS 18.0 also fails to connect to the same Wi-Fi network. However, if I restart the Wi-Fi router, the non-iPhone 16 series devices can successfully connect to the Wi-Fi network. To further investigate, I used Wireshark to monitor the network traffic. I observed that the iPhone sends a DHCP Discover message, but the Wi-Fi router does not respond with a DHCP Offer message. Based on these observations, it appears that the issue is triggered by the iPhone 16 series running iOS 18.0, which causes the Wi-Fi router to malfunction and prevents other devices from connecting. Additionally, I have tried all the steps listed on the following site, but the issue persists: https://support.apple.com/en-us/111786 Could you please investigate this issue and provide guidance on how to resolve it? If this is a known bug, is there a planned update to address it? Thank you for your assistance. I look forward to your prompt response. Best regards, WJohn
2
0
120
2d
Which thread to call uploadTask from URLSession
Hi, I would like to know if it is safe to call the uploadTask from URLSession from the main thread ? We've a user who is reporting repeated crashes at startup, here is the stack we see: Exception Type: EXC_CRASH (SIGKILL) Exception Codes: 0x0000000000000000, 0x0000000000000000 Termination Reason: FRONTBOARD 2343432205 <RBSTerminateContext| domain:10 code:0x8BADF00D explanation:scene-update watchdog transgression: app<com.appspot.myApp(E7590BB1-722C-491D-9199-F867DE4B880A)>:2212 exhausted real (wall clock) time allowance of 10.00 seconds ProcessVisibility: Background ProcessState: Running WatchdogEvent: scene-update WatchdogVisibility: Background WatchdogCPUStatistics: ( "Elapsed total CPU time (seconds): 21.260 (user 10.230, system 11.030), 35% CPU", "Elapsed application CPU time (seconds): 0.006, 0% CPU" ) reportType:CrashLog maxTerminationResistance:Interactive> Triggered by Thread: 0 Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0 Crashed: 0 libsystem_kernel.dylib 0x1def7a688 mach_msg2_trap + 8 1 libsystem_kernel.dylib 0x1def7dd98 mach_msg2_internal + 80 2 libsystem_kernel.dylib 0x1def7dcb0 mach_msg_overwrite + 424 3 libsystem_kernel.dylib 0x1def7dafc mach_msg + 24 4 libdispatch.dylib 0x1968d8f14 _dispatch_mach_send_and_wait_for_reply + 544 5 libdispatch.dylib 0x1968d92b4 dispatch_mach_send_with_result_and_wait_for_reply + 60 6 libxpc.dylib 0x21714a930 xpc_connection_send_message_with_reply_sync + 256 7 Foundation 0x18d80a3ac __NSXPCCONNECTION_IS_WAITING_FOR_A_SYNCHRONOUS_REPLY__ + 16 8 Foundation 0x18d806b14 -[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:] + 2160 9 CoreFoundation 0x18eb868dc ___forwarding___ + 1004 10 CoreFoundation 0x18eb86430 _CF_forwarding_prep_0 + 96 11 CFNetwork 0x1900c71e0 -[__NSURLBackgroundSession setupBackgroundSession] + 800 12 CFNetwork 0x1900b3e80 -[__NSURLBackgroundSession initWithConfiguration:delegate:delegateQueue:delegateDispatchQueue:] + 552 13 CFNetwork 0x1900b4784 +[NSURLSession _sessionWithConfiguration:delegate:delegateQueue:delegateDispatchQueue:] + 1496 14 MyApp 0x1054210b4 CombineBgXferRepository.session.getter (in MyApp) (CombineBgXferRepository.swift:62) + 7966900 15 MyApp 0x105422fa4 CombineBgXferRepository.startUploadTask(fileURL:request:) (in MyApp) (CombineBgXferRepository.swift:310) + 7974820 If it is ok to call this uploadTask from the main thread, does this crash indicate a problem with the operating system? Are there scenarios where the background upload service does not respond to requests?
3
2
114
2d
Intermittent failure to connect to a hidden AP when connecting programmatically
Hello there! We have an app that connects to an external device via Wi-Fi to send and query content from it. This external device generates a hidden AP that the phone connects against. However, sometimes the app fails to connect to the external device with the system alert "Unable to join the network...". We have been debugging for a couple but couldn't find any clear reason of why this thing is happening. What could be the reason behind this alert appearing? For the connection, we are using the NEHotspotConfigurationManager to connect to the AP of this external device. The configuration for the connection is the following: NEHotspotConfiguration( ssid: ssid, passphrase: password, isWEP: false ) configuration.hidden = true There are some logs that we extracted that show two connections. One happened at 20:37, which was a successful connection. wifi_logs_success 2.log Another connection was made at 20:38, which failed. wifi_logs_failure.log Inspecting the logs, one difference that I see between them is the __WiFiDeviceManagerDispatchUserForcedAssociationCallback: result %lld, which in the successful case is 0 and in the failed case is 1. Can anyone help with this? We're very lost on why this configuration could be an issue at all.
1
0
94
3d
Send UDP Protocol is not working in Xcode 16 iOS18
func setupUDPSocket() { stopSearch() udpSocket = GCDAsyncUdpSocket(delegate: self, delegateQueue: DispatchQueue.main) do { try udpSocket?.bind(toPort: 4012) try udpSocket?.beginReceiving() try udpSocket?.joinMulticastGroup("239.255.255.250") } catch let error { DispatchQueue.main.async { print(Thread.current) print(error) print(error) } } } private func search() { guard let udpSocket = udpSocket else { print("not set udpSocket") stopSearch() return } let message = "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "MAN: \"ssdp:discover\"\r\n" + "MX: 3\r\n" + "ST: ssdp:all\r\n" + "\r\n" let data = message.data(using: .utf8)! udpSocket.send(data, toHost: "239.255.255.250", port: 1900, withTimeout: -1, tag: 0) } This is my send SSDP code, my project was inited in Objective-C, recently I update xcode to 16, I get Error Domain=NSPOSIXErrorDomain Code=65 "No route to host", when I send UPD data in iOS 18, but iOS 17 is ok. Even I found, if I init a new project in Swift, this bug is disappear.
1
0
109
6d
Significant Decrease in Network Speed After Replacing NSURLConnection with NSURLSession
Hello, I recently replaced NSURLConnection with NSURLSession in my application, and I have noticed a significant decrease in network speed. I am seeking advice on why this might be happening and how to resolve the issue. Here is the code before the change: Old Code: - (void)execute:(id<STHttpEntity>)entity { [entity addHeader:API_HDR_CLASS_NAME value:self.apiClass]; [entity addHeader:API_HDR_METHOD_NAME value:self.apiMethod]; NSMutableURLRequest *req = [self createRequest:entity]; self.connection = [[NSURLConnection alloc] initWithRequest:req delegate:self]; [self.connection start]; } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { [self clearConnectionTimeout]; self.requestData = nil; if (self.httpStatus != HTTPSTATUS_OK) { [self callFailedWithStatus:self.httpStatus]; return; } [self callSucceeded]; } And here is the code after the change: New Code: - (void)execute:(id<STHttpEntity>)entity { [entity addHeader:API_HDR_CLASS_NAME value:self.apiClass]; [entity addHeader:API_HDR_METHOD_NAME value:self.apiMethod]; NSMutableURLRequest *req = [self createRequest:entity]; NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil]; self.dataTask = [session dataTaskWithRequest:req]; [self.dataTask resume]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error { [self clearConnectionTimeout]; self.requestData = nil; if (error) { [self callFailed:error]; } else { [self callSucceeded]; } } Issue: After replacing NSURLConnection with NSURLSession, the network speed has significantly decreased. The new implementation seems to be much slower than the old one. Questions: 1.What could be the reasons for the significant decrease in network speed after switching to NSURLSession? 2.Are there any specific configurations or best practices for NSURLSession that I should be aware of to improve performance? 3.Is there any known issue with NSURLSession that could cause such a performance drop? Any insights or suggestions would be greatly appreciated. Thank you in advance for your help!
1
0
107
6d
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
138
13h
Custom Property when creating a NWConnection
I am developing an App using the Networking framework, which can be either a Socket Server or a Socket Client, such that 2 devices can communicate remotely. I would like to include the Client's userUID when creating a NWConnection, such that when the SocketServer accepts the connection, it knows immediately which user is connected. (Currently I achieve this by sending the UserUID in Welcome/Introduction messages, which seems an unnecessary overhead, and because I am using UDP, I also have to make sure these messages are acknowledged, before safely using the connection.) Is there a way to add this custom data into the NWConnection?
2
0
132
1w
IP Address for Socket Server and Client
I am developing an App using the Networking framework, which can be either a Socket Server or a Socket Client, such that 2 devices can communicate remotely. For the most part I have it working, except: I am not sure of the best way to determine the IP Address for the Socket Server in order to allow the Client app to connect. I am currently using either of Cloud Functions, or lookup webpages (such as ipify.org) and even reading the IP addresses locally from within the device (this returns many, but not all of them connect successfully). These options seem to work if the Socket Server app is connected to the internet with an IPv6 address, but I find that when the Socket Server app is connected with an IPv4 address, the Client app never successfully connects. How should I: a) force the Socket Server app to have/use an IPV6 address at all times? or b) allow the Client app to connect successfully via an IPv4 address? And is there a simple way to know what IP Address the Socket Server is listening from?
4
0
132
1w
Subscribe to an existing JMS provider
I need to connect to a JMS that publishes data that I need to collect. I am trying one solution: RabbitMQ with the JMS plugin. I succeeded to install RabbitMQ and send messages from one process to another. However, I need to consume a JMS that an external party publishes. Can anybody tell me how I should configure the Host, Port, Username, Password and Queue name for RabbitMQ/JMS so that I can consume (or subscribe to) that JMS? Or does anybody know another way to consume (or subscribe to) a JMS from Swift? I have no idea which of the provided Tags I should select. Thanks! Wouter
5
0
157
2w
Prioritizing QUIC streams?
When creating multiple QUIC streams (NWConnections) sharing one QUIC tunnel (using NWMultiplexGroup), is it possible to assign different priorities to the streams? And if yes, how? The only prioritization option I found so far is NWConnection.ContentContext.relativePriority, but I assume that is for prioritizing messages within a single NWConnection?
5
0
175
1w
the app in ipad(ios 18) can not connect to tcp server in the same local network
the app in ipad can not connect to tcp server in the same local network. libinfo check path: unsatisfied (Local network prohibited) reproduce steps: I update my ipad to iapd iOS/18.0 install the app make the app connect to tcp server in the windows which is in the same local network. the ipad trigger Local Network privacy alert I tap the allow button, I check the toggle of Local Network privacy is on as well I try to make the app connect to tcp server in the windows again, but can not connect to tcp server, the ipad system log: nw_path_libinfo_path_check [8F864AB4-C5E1-488D-B396-ECEC2F3FB77E IPv4#0423cc45:9520 tcp, legacy-socket, attribution: developer] libinfo check path: unsatisfied (Local network prohibited), interface: en0[802.11], ipv4, uses wifi 7. I try to make the app connect to tcp server in other windows. It connects successful. the ipad system log: nw_path_libinfo_path_check [C84DC25A-5A14-4080-ABAA-10ED24AE2D6D IPv4#7df62769:9520 tcp, legacy-socket, attribution: developer] libinfo check path: satisfied (Path is satisfied), interface: en0[802.11], ipv4, dns, uses wifi So please apple developer help investigate why the app can not connect to the tcp sever in the same local network, even though the toggle of local network permission is on in ipad os 18
2
0
153
2w
How to transition from a non-background upload to a background one
A few months ago, I remember reading some official documentation that was describing how to switch to a background upload when the app is about to be suspended. Unfortunately, I can't find that resource back, so it would be fantastic if someone would point it out to me. If I remember correctly, the procedure described was to start a regular upload task within some UIApplication.backgroundTask, and in any case the upload wasn't finished at the moment the system would call the suspension handler, the upload was "transitioned" into a a background one while preserving the current progress (I think because it was using the same URLSession or something, hence why I want to find back the documentation!) Note that I don't want to start a background upload from the beginning (this is what we do already!). I'm mostly looking for that piece of documentation to experiment if that scheme would improve our upload performance. Thanks!
1
0
143
2w
iOS app that can support multiple hardware devices simultaneously
Hello, I am planning to create an app that can transfer files to hardware devices via WiFi. With devices like GoPro, I believe the typical setup involves the GoPro creating a WiFi hotspot to which the iOS app connects, allowing file transfers. But this setup establishes a 1:1 connection between the app and the hardware. To support multiple hardware devices simultaneously, I am considering reversing this setup: the iOS device would create a personal hotspot, and the hardware devices would connect to it. However, I have concerns about this approach: Reliability: I have read that the personal hotspot feature on iOS devices can be unreliable, especially with non-Apple devices, which tend to disconnect frequently. Manual Setup: There is no API to programmatically create the personal hotspot, so users would have to enable it manually in the Settings. I can use isIdleTimerDisabled to prevent the iOS screen from going to sleep, which might help with disconnection issues. Aside from this, are there other things I can do to ensure a stable connection? Given my limited experience with hardware connections, I am uncertain if having the iOS device act as the WiFi access point is a good design. Any advice or alternative solutions would be greatly appreciated. Thank you in advance!
4
0
231
2w
How to Reply to a Message Received by Multicast Receiver and Extract Connection for Communication
Hello everyone, I’m currently working on a Swift project using the Network framework to create a multicast-based communication system. Specifically, I’m implementing both a multicast receiver and a sender that join the same multicast group for communication. However, I’ve run into some challenges with the connection management, replying to multicast messages, and handling state updates for both connections and connection groups. Below is a breakdown of my setup and the specific issues I’ve encountered. I have two main parts in the implementation: the multicast receiver and the multicast sender. The goal is for the receiver to join the multicast group, receive messages from the sender, and send a reply back to the sender using a direct connection. Multicast Receiver Code: import Network import Foundation func setupMulticastGroup() -> NWConnectionGroup? { let multicastEndpoint1 = NWEndpoint.hostPort(host: NWEndpoint.Host("224.0.0.1"), port: NWEndpoint.Port(rawValue: 45000)!) let multicastParameters = NWParameters.udp multicastParameters.multipathServiceType = .aggregate do { let multicastGroup = try NWMulticastGroup(for: [multicastEndpoint1], from: nil, disableUnicast: false) let multicastConnections = NWConnectionGroup(with: multicastGroup, using: multicastParameters) multicastConnections.stateUpdateHandler = InternalConnectionStateUpdateHandler multicastConnections.setReceiveHandler(maximumMessageSize: 16384, rejectOversizedMessages: false, handler: receiveHandler) multicastConnections.newConnectionHandler = newConnectionHandler multicastConnections.start(queue: .global()) return multicastConnections } catch { return nil } } func receiveHandler(message: NWConnectionGroup.Message, content: Data?, isComplete: Bool) { print("Received message from \(String(describing: message.remoteEndpoint))") if let content = content, let messageString = String(data: content, encoding: .utf8) { print("Received Message: \(messageString)") } let remoteEndpoint = message.remoteEndpoint message.reply(content: "Multicast group on 144 machine ACK from recv handler".data(using: .utf8)) if let connection = multicastConnections?.extract(connectionTo: remoteEndpoint) { connection.stateUpdateHandler = InternalConnectionRecvStateUpdateHandler connection.start(queue: .global()) connection.send(content: "Multicast group on 144 machine ACK from recv handler".data(using: .utf8), completion: NWConnection.SendCompletion.contentProcessed({ error in print("Error code: \(error?.errorCode ?? 0)") print("Ack sent to \(connection.endpoint)") })) } } func newConnectionHandler(connection: NWConnection) { connection.start(queue: .global()) connection.send(content: "Multicast group on 144 machine ACK".data(using: .utf8), completion: NWConnection.SendCompletion.contentProcessed({ error in print("Error code: \(error?.errorCode ?? 0)") print("Ack sent to \(connection.endpoint)") })) } func InternalConnectionRecvStateUpdateHandler(_ pState: NWConnection.State) { switch pState { case .setup: NSLog("The connection has been initialized but not started") case .preparing: NSLog("The connection is preparing") case .waiting(let error): NSLog("The connection is waiting for a network path change. Error: \(error)") case .ready: NSLog("The connection is established and ready to send and receive data.") case .failed(let error): NSLog("The connection has disconnected or encountered an error. Error: \(error)") case .cancelled: NSLog("The connection has been canceled.") default: NSLog("Unknown NWConnection.State.") } } func InternalConnectionStateUpdateHandler(_ pState: NWConnectionGroup.State) { switch pState { case .setup: NSLog("The connection has been initialized but not started") case .waiting(let error): NSLog("The connection is waiting for a network path change. Error: \(error)") case .ready: NSLog("The connection is established and ready to send and receive data.") case .failed(let error): NSLog("The connection has disconnected or encountered an error. Error: \(error)") case .cancelled: NSLog("The connection has been canceled.") default: NSLog("Unknown NWConnection.State.") } } let multicastConnections = setupMulticastGroup() RunLoop.main.run() Multicast Sender Code: import Foundation import Network func setupConnection() -> NWConnection { let params = NWParameters.udp params.allowLocalEndpointReuse = true return NWConnection(to: NWEndpoint.hostPort(host: NWEndpoint.Host("224.0.0.1"), port: NWEndpoint.Port(rawValue: 45000)!), using: params) } func sendData(using connection: NWConnection, data: Data) { connection.send(content: data, completion: .contentProcessed { nwError in if let error = nwError { print("Failed to send message with error: \(error)") } else { print("Message sent successfully") } }) } func setupReceiveHandler(for connection: NWConnection) { connection.receive(minimumIncompleteLength: 1, maximumLength: 65000) { content, contentContext, isComplete, error in print("Received data:") print(content as Any) print(contentContext as Any) print(error as Any) setupReceiveHandler(for: connection) } } let connectionSender = setupConnection() connectionSender.stateUpdateHandler = internalConnectionStateUpdateHandler connectionSender.start(queue: .global()) let sendingData = "Hello, this is a multicast message from the process on mac machine 144".data(using: .utf8)! sendData(using: connectionSender, data: sendingData) setupReceiveHandler(for: connectionSender) RunLoop.main.run() Issues Encountered: Error Code 0 Even When Connection Refused: On the receiver side, I encountered this log: nw_socket_get_input_frames [C1.1.1:1] recvmsg(fd 8, 9216 bytes) [61: Connection refused] Error code: 0 Ack sent to 10.20.16.144:62707 Questions: how do I reply to the message if above usage pattern is wrong? how do I get a NWConnection from the received message to create a separate connection for communication with the sender. Any insights or suggestions on resolving these issues or improving my multicast communication setup would be greatly appreciated. Thanks :)
2
0
171
2w
Why is there a 1 second delay when sending or receiving from a socket?
I am creating a VoIP application. The VoIP application needs to send and receive RTP packets at 20 ms intervals. The application calls sendto() of the Socket API at 20 ms intervals, but the iPhone buffers the send data inside iOS and then sends RTP packets in batches at 1 second intervals. (I captured the sned packets of iPhone with rvctl and confirmed this. please reffer "Sending at 1 second intervals.png" for detail) Similarly, other devices send RTP packets to the iPhone at 20 millisecond intervals, but the iPhone only receives them at 1 second intervals. (please reffer "Receiving at 1 second intervals.png" for detail) Why is this? If the cause of the delay is in the Wi-Fi protocol and the cause can be found from sysdiagnose, please tell me the search key for sysdiagnose that shows the cause of the delay and the meaning of the corresponding log. I uploaded sysdiagnose and result of lan capture to below. [sysdiagnose and lan capture] https://drive.google.com/file/d/149OPmePAF4hnZj6NeSnKc5NizfitPQDS/view?usp=sharing And, the start and end times, packet number in the lan capture of the call shown in the png example are below Start time; 13:57:22.349608/packet number; 948 End time; 13:57:37.482874/packet number; 2583
6
0
174
2w