从 NWConnection 获取 IP 地址的正确方法是什么

vpo*_*ave 4 networking ios swift

我正在使用 NWListenernewConnectionHandler处理程序来获取 newConnection,如下所示:

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)
}
Run Code Online (Sandbox Code Playgroud)

这是打印: 10.0.1.2:62610

我只需要获取ip 地址,以便稍后保存,但我无法在其中找到任何属性NWEndpoint来获取它。我可以做这样的事情:

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

但我一点也不喜欢它。获取ip地址的正确方法是什么?

谢谢。

Mar*_*n R 8

NWEndpoint是不同类型端点的枚举(具有关联值)。接受的 TCP 连接的远程主机将是由主机和端口定义的端点,您可以使用 switch 语句来提取这些值。

如果您只想要主机部分的字符串表示形式,而不需要端口,那么它将是

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