Do a simple DNS lookup in Swift

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-06 14:51:45

问题


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


来源:https://stackoverflow.com/questions/24898001/do-a-simple-dns-lookup-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!