Ios 从NWConnection获取ip地址的正确方法是什么
我正在使用NWListenerIos 从NWConnection获取ip地址的正确方法是什么,ios,swift,networking,Ios,Swift,Networking,我正在使用NWListenernewConnectionHandlerhandler获得如下新连接: listener.newConnectionHandler = { [weak self] newConnection in guard let self = self else { return } newConnection.stateUpdateHandler = { [weak self] newState in guard let self = sel
newConnectionHandler
handler获得如下新连接:
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)
}
var ipAddressWithPort = newConnection.endpoint.debugDescription
if let portRange = ipAddressWithPort.range(of: ":") {
ipAddressWithPort.removeSubrange(portRange.lowerBound..<ipAddressWithPort.endIndex)
}
这是印刷品:
10.0.1.2:62610
我需要只获取ip地址,以便以后保存,但我无法在NWEndpoint
中找到任何属性来获取它。我可以这样做:
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)
}
var ipAddressWithPort = newConnection.endpoint.debugDescription
if let portRange = ipAddressWithPort.range(of: ":") {
ipAddressWithPort.removeSubrange(portRange.lowerBound..<ipAddressWithPort.endIndex)
}
var ipAddressWithPort=newConnection.endpoint.debugDescription
如果let portRange=ipAddressWithPort.range(of:“”){
ipAddressWithPort.removeSubrange(portRange.lowerBound..NWEndpoint
是不同类型端点的枚举(带有关联值)。接受TCP连接的远程主机将是由主机和端口定义的端点,您可以使用switch语句提取这些值
如果您只需要主机部件的字符串表示,而不需要端口,那么
switch(connection.endpoint) {
case .hostPort(let host, _):
let remoteHost = "\(host)"
print(remoteHost) // 10.0.1.2
default:
break
}