NWConnection.currentPath?.localEndpoint returns 192.168.1.X:YYYYY. I'd like to listen to port YYYYY for a reply after sending from that port to a multicast address but I can't seem to extract that data separately.
NWEndpoint is an enumeration and .hostPort is a case as hostPort(host: NWEndpoint.Host, port: NWEndpoint.Port) . The documentation reference doesn't show any getter functions, so how can I elegantly get only the port number?
I can convert it to a string with String(describing: NWEndpoint) and handle the string from there, but I'd preferably like a native Network framework method.
NWEndpoint is an enum, so you can extract values using a switch statement. For example:
import Network
func portForEndpoint(_ endpoint: NWEndpoint) -> NWEndpoint.Port? {
switch endpoint {
case .hostPort(_, let port):
return port
default:
return nil
}
}
print(portForEndpoint(NWEndpoint.hostPort(host: "example.com", port: 12345)))
// prints: Optional(12345)
ps If you have any more questions about Network framework, I recommend that you ask them over on DevForums, and specifically in the Core OS > Networking topic area.
Thank you so much! I'm fairly new to Swift (and programming) in general and had never used enums before. Thanks for the recommendation about networking, too.