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)")
}
}
}