我可以在我的 Swift 项目中使用 Objective-C 代码从 NSNetService 获取 IP 地址。是否有 Swift 代码可以做同样的事情(以避免出现桥接头)?否则我会保持现在的方式 - 但希望它可以在 Swift 中完成。
-(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";
}
更新的代码有效:
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)")
}
}
}