Sender IP address in UDP

When receiving a UDP packet using NWConnection.receiveMessage(), how can I find the sender's IP address?
For example, in C, the recvfrom() function writes the sender IP and port to a struct sockaddr that I can later examine. Is there something equivalent in Swift?
A UDP NWConnection always represents a flow of datagrams, that is, it always has the same source IP/destination IP/source port/destination port tuple. You can access the destination IP and port using the connection’s endpoint property.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
@eskimo That's what I tried, (from here https://developer.apple.com/documentation/network/nwendpoint), but when I type
Code Block
incomingConnection.endpoint.IPv4Address
it says "Value of type NWEndpoint has no member IPv4Address". In other words, I don't see how to get the IP address or port out of endpoint.

NWEndpoint is an enum that supports multiple different cases. In this specific instance, however, it’ll always be the .hostPort(host:port:) case. You can extract the associated host and port values with code like this:

Code Block
guard case .hostPort(host: let host, port: let port) = endpoint else { fatalError() }


You’ll have to decide what to do if you get one of the other cases. In my code I typically just fatalError because I can’t imagine a situation where this would fail.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
Sender IP address in UDP
 
 
Q