Do a simple DNS lookup in Swift

2019-08-27 21:56发布

问题:

I am trying to do a simple DNS lookup with Swift code. So far, I have

    if  host != "\0" {
        let hostRef = CFHostCreateWithName(kCFAllocatorDefault, host.bridgeToObjectiveC()).takeRetainedValue()
        var resolved = CFHostStartInfoResolution(hostRef, CFHostInfoType.Addresses, nil)
        let addresses = CFHostGetAddressing(hostRef, &resolved).takeRetainedValue() as NSArray

        for address: AnyObject in addresses {
            println(address)  // address is of type NSData.
        }
    }

as per Convert NSData to sockaddr struct in swift. (host is an NSString.)

However, my debugger log prints <10020000 4a7de064 00000000 00000000>, before exiting with an EXC_BAD_ACCESS (code=EXC_I386_GPFLT) on the first line, AFTER executing the if statement and printing the address data. All I'm trying to get is a string with an IP address, or if the host does not exist, a null string.

回答1:

I have tested and found that AnyObject is casuse of crash.You do not need AnyObject as swift will infer type from array addresses

var host = "192.168.103.13"
    if  host != "\0" {
        let hostRef = CFHostCreateWithName(kCFAllocatorDefault, host.bridgeToObjectiveC()).takeRetainedValue()
        var resolved = CFHostStartInfoResolution(hostRef, CFHostInfoType.Addresses, nil)
        let addresses = CFHostGetAddressing(hostRef, &resolved).takeRetainedValue() as NSArray

        println(addresses)
        //Remove `AnyObject` as there is no need.Swift will infrence from array addresses
        for address in addresses {
            println(address)  // address is of type NSData.
        }
    }