Created
January 23, 2020 11:07
-
-
Save stropdale/f63af45645be5b6d32fe6f359d0f6588 to your computer and use it in GitHub Desktop.
Swift Reverse DNS Lookup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
func reverseDNS(ip: String) -> String { | |
var results: UnsafeMutablePointer<addrinfo>? = 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<Int8>.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 | |
} | |
var host = "192.168.86.111" | |
reverseDNS(ip: host) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment