How to get Domain Name of IP address and IP address from Domain Name in Objective C?

前端 未结 3 1333
醉酒成梦
醉酒成梦 2020-12-06 08:25

I am able to get the current IP address of my device/machine that I am using - by using this question\'s answer.

I have gone through this question. Java allows to ge

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-06 09:19

    I wrote a Swift version of the accepted answer, though I'm not 100% sure of its correctness.

    func reverseDNS(ip: String) -> String {
        var results: UnsafeMutablePointer? = nil
        defer {
            if let results = results {
                freeaddrinfo(results)
            }
        }
        let error = getaddrinfo(ip, nil, nil, &results)
        if (error != 0) {
            print("Unable to reverse ip: \(ip)")
            return ip
        }
    
        for addrinfo in sequence(first: results, next: { $0?.pointee.ai_next }) {
            guard let pointee = addrinfo?.pointee else {
                print("Unable to reverse ip: \(ip)")
                return ip
            }
    
            let hname = UnsafeMutablePointer.allocate(capacity: Int(NI_MAXHOST))
            defer {
                hname.deallocate()
            }
            let error = getnameinfo(pointee.ai_addr, pointee.ai_addrlen, hname, socklen_t(NI_MAXHOST), nil, 0, 0)
            if (error != 0) {
                continue
            }
            return String(cString: hname)
        }
    
        return ip
    }
    

提交回复
热议问题