问题
I am trying to use CFHostGetAddressing to do a simple DNS lookup. However, I notice that it returns an array of sockaddr structs, which I guess means it can only do IPV4.
Is there a way to support DNS entries with IPV6 addresses in iOS? Perhaps a similar API that returns an array of sockaddr_storage structs?
回答1:
The CFHostGetAddressing()
documentation might be misleading, because struct sockaddr
is a structure that covers all the common elements of the various socket addresses (IPv4, IPv6, ...). It is usually only used to pass a generic pointer to the socket functions.
Actually CFHostGetAddressing()
works well with IPv6. It returns an array of CFData
elements where each element contains a struct sockaddr_in
or a struct sockaddr_in6
.
Using the code from your previous question as a starting point, the following should work:
let hostRef = CFHostCreateWithName(kCFAllocatorDefault, "localhost").takeRetainedValue()
var resolved = CFHostStartInfoResolution(hostRef, CFHostInfoType.Addresses, nil)
let addresses = CFHostGetAddressing(hostRef, &resolved).takeRetainedValue() as NSArray
for addr in addresses as [NSData] {
var sockaddr = UnsafePointer<sockaddr_storage>.alloc(1)
addr.getBytes(sockaddr, length: sizeof(sockaddr_storage))
// ...
sockaddr.destroy()
}
来源:https://stackoverflow.com/questions/24796142/does-cfhostgetaddressing-support-ipv6-dns-entries