在Swift中进行简单的DNS查找

时间:2014-07-22 21:17:13

标签: macos dns swift nsdata nslookup

我正在尝试使用Swift代码进行简单的DNS查找。到目前为止,我有

    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.
        }
    }

根据Convert NSData to sockaddr struct in swift。 (hostNSString。)

但是,在执行<10020000 4a7de064 00000000 00000000>语句并打印EXC_BAD_ACCESS (code=EXC_I386_GPFLT)数据后,我的调试器日志在第一行退出if之前打印address。我试图获取的是一个带有IP地址的字符串,或者如果主机不存在,则为空字符串。

1 个答案:

答案 0 :(得分:0)

我已经测试过,发现AnyObject已经崩溃了。你不需要AnyObject因为swift会从数组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.
        }
    }