Radagast the Brown
Radagast the Brown

Reputation: 407

Swift IP Address from NSNetService

I am able to get the IP Address from NSNetService using Objective-C code in my Swift project. Is there Swift code that can do the same (to avoid having a bridging header)? Otherwise I'll keep the way I'm doing it now - but hoping it can be done in Swift instead.

-(NSString* )IPAddressesFromData:(NSNetService *)service {
    for (NSData *address in [service addresses]) {
        struct sockaddr_in *socketAddress = (struct sockaddr_in *) [address bytes];
        //NSLog(@"Service name: %@ , ip: %s , port %i", [service name], inet_ntoa(socketAddress->sin_addr), [service port]);
        NSString *retString = [NSString stringWithFormat:@"%s", inet_ntoa(socketAddress->sin_addr)];
        return retString;
    }
    return @"Unknown";
}

Updated code which works:

func netServiceDidResolveAddress(sender: NSNetService) {
    let theAddress = sender.addresses!.first! as NSData
    var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0)
    if getnameinfo(UnsafePointer(theAddress.bytes), socklen_t(theAddress.length),
                   &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 {
        if let numAddress = String.fromCString(hostname) {
            print("Resolved IP address: \(numAddress)")
        }
    }
}

Upvotes: 2

Views: 1476

Answers (1)

LaiBit
LaiBit

Reputation: 11

You can use:

func netServiceDidResolveAddress(_ sender: NetService) {

    var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
    guard let data = sender.addresses?.first else { return }
    do {
        try data.withUnsafeBytes { (pointer:UnsafePointer<sockaddr>) -> Void in
            guard getnameinfo(pointer, socklen_t(data.count), &hostname, socklen_t(hostname.count), nil, 0, NI_NUMERICHOST) == 0 else {
                throw NSError(domain: "domain", code: 0, userInfo: ["error":"unable to get ip address"])
            }
        }
    } catch {
        print(error)
        return
    }
    let address = String(cString:hostname)
    print("\(sender.name)  IP:\(address)")

}

Upvotes: 1

Related Questions