How to get UDP sender address using Network.framework

I need to implement a custom discovery protocol using UDP. It works like this:
  1. You broadcast a beacon to a broadcast address (like 255.255.255.255).

  2. You wait for clients that respond to your beacon.

The problem is: how can I get the addresses of the clients once they send their response?

Sending

I sent the beacon like this:
Code Block
let connection = NWConnection(
to: .hostPort(
host: .ipv4(.broadcast),
port: .init(integerLiteral: discoveryPort)
),
using: .udp
)
connection.start(queue: .main)
connection.send(
content: beacon,
completion: .contentProcessed(sendCompleted)
)

Receiving

To receive the responses from the clients I use
Code Block
connection.receiveMessage {
(message: Data?, context: NWConnection.ContentContext?, isComplete: Bool, optionalError: NWError?) in
// Great I got a response...
// But how do I know where this is coming from?
}

Replies

In general, the remote side of a connection can be accessed on connection.currentPath.remoteEndpoint.

In the example you give, are you receiving this connection from a UDP NWListener that gets the responses to your broadcast message?
Hi thanks for the response.
connection.currentPath.remoteEndpoint is the broadcast address in my example.

I didn't use an NWListener, I called receiveMessage on the NWConnection from which I am sending the beacons. I did this because I need to listen to the port from which the beacons are sent.

How do I create a NWListener that binds to the same port my NWConnection uses to send the beacon?