What is proper way to get ip address from NWConnection

Viewed 1050

I'm using NWListener newConnectionHandler handler to get newConnection like this:

listener.newConnectionHandler = { [weak self] newConnection in
    guard let self = self else { return }

    newConnection.stateUpdateHandler = { [weak self] newState in
        guard let self = self else { return }
        ...
        ...
        print("Connection endpoint: \(newConnection.endpoint)")
    }

    newConnection.start(queue: self.queue)
}

This is prints: 10.0.1.2:62610

I need to get just ip address, to save it for later, but I wasn't able to find any property inside NWEndpoint to get it. I can do something like this:

var ipAddressWithPort = newConnection.endpoint.debugDescription
if let portRange = ipAddressWithPort.range(of: ":") {
    ipAddressWithPort.removeSubrange(portRange.lowerBound..<ipAddressWithPort.endIndex)
}

But I don't like it at all. What is proper way to get ip address?

Thank you.

1 Answers

NWEndpoint is an enumeration (with associated values) for the different kinds of endpoints. The remote host of an accepted TCP connection will be an endpoint defined by host and port, and you can use a switch statement to extract those values.

If you just want a string representation of the host part, without the port, it would be

switch(connection.endpoint) {
    case .hostPort(let host, _):
        let remoteHost = "\(host)"
        print(remoteHost) // 10.0.1.2
    default:
        break
}
Related