I'm struggling to use NWListener and NWConnection on the same port.
I have a simple task requires that I send out a UDP datagram to the broadcast address, and expect to receive replies on the port which sent the datagram. In Blue Sockets, I can create a socket, send out the broadcast message and listen and accept connections on the same socket.
In wireshark the exchange looks like:
10.0.0.123 255.255.255.255 UDP 71 62003 -> 9000 Len=29
10.0.0.202 10.0.0.123 UDP 1060 9000 -> 62003 Len=101
However after hours of experimentation in a swift playground, I am not able to create an NWListener and an NWConnection on the same socket.
Here are the salient pieces of code:
let udpListener = try! NWListener(using: .udp)
... setup and start listener
let broadcast: NWEndpoint.Host = "255.255.255.255"
let portUDP: NWEndpoint.Port = 9000
let localPort : NWEndpoint.Port = udpListener!.port!
let localEndpoint = NWEndpoint.hostPort(host: "10.0.0.123", port: localPort)
let parameters = NWParameters.udp
parameters.requiredLocalEndpoint = localEndpoint
let connection = NWConnection(host: broadcast, port: portUDP, using: parameters)
However creating the NWConnection on the same port as the NWListener gives an error that the port is in use. I've tried the reverse, createing the connection on a known port, closing it and starting a listener immediately affterwards on that same port, but that also results in an error.
How can I implement this very simple protocol using the Network API ? Are there some options I need to set ?
Thanks for any help.
Guy