How to get ipAdress from NWListener and NWBrowser

NetServiceBrowser has 2 delegate functions. The first delegate gets called when it discovers a service netServiceBrowser(: didFind: moreComing: ) and the second delegate (below) gets triggered when the address is resolved. You can use that delegate to get the ipaddress:


func netServiceDidResolveAddress(_ sender: NetService) {
    print("did resolve address")

    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
      
    guard let data = sender.addresses?.first else { print("guard let data failed"); return }
      
    data.withUnsafeBytes { (pointer: UnsafeRawBufferPointer) -> Void in
        let sockaddrPtr = pointer.bindMemory(to: sockaddr.self)
        guard let unsafePtr = sockaddrPtr.baseAddress else { return }
        guard getnameinfo(unsafePtr, socklen_t(data.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else {
            return
        }
    }
   
    let ipAddress = String(cString:hostname)
    print(ipAddress)
}


How can i get the ipAddress when a NWBrowser connects with a NWListener and the NWListener responds back to the NWBrowser?


Listener/Advertiser:

var listener: NWListener?
listener?.newConnectionHandler = { (nwConnection) in
    // new connection and/or data came in from Browser, what is its ipAddress?
}


Browser:

var browser: NWBrowser?
var connection: NWConnection?

browser?.browseResultsChangedHandler = { (results, changes) in
    for result in results {
        // Advertiser endpoint found, what is its ipAdress?
        print(result.endpoint.debugDescription)
    }
}

connection?.receiveMessage { (content, _, _, error) in
    if let messageData = content {
        // received data from Advertiser, what is its ipAddress?
    }
}

Accepted Reply

For NWListener and NWBrowser the NWEndpoint information is provided describing the service type, transport protocol, address family, interface etc... There is no explicit IP address provided because that is not done until the actual NWConnection is made to the service endpoint. Quinn has an excellent explanation for a related question in apost found here.



Matt Eaton

DTS Engineering, CoreOS

meaton3 at apple.com

Replies

For NWListener and NWBrowser the NWEndpoint information is provided describing the service type, transport protocol, address family, interface etc... There is no explicit IP address provided because that is not done until the actual NWConnection is made to the service endpoint. Quinn has an excellent explanation for a related question in apost found here.



Matt Eaton

DTS Engineering, CoreOS

meaton3 at apple.com

Thanks for the response and link!