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
You need to read the routing table - basically the same way as "netstat -r" command does. The netstat implementation is opensource - it's in the package
network_cmds-396.6
at
http://www.opensource.apple.com/release/mac-os-x-1082/
so you can check what it does. The default gateway contains the "G" flag but shouldn't connect the "I" flag (when both wifi and cell are active, wifi is used for internet connection - the cell gateway is not used and is given the "I" flag).
Hope it helps.
I'm not sure if this is the best way to do this, but it works for me, mostly. I put in StackOverflow's IP addresses (69.59.196.211) and it gave me back stackoverflow.com
, but I put in one of Google's IP addresses (210.55.180.158) and it gave me back cache.googlevideo.com
(for all results, not just the first one).
int error;
struct addrinfo *results = NULL;
error = getaddrinfo("69.59.196.211", NULL, NULL, &results);
if (error != 0)
{
NSLog (@"Could not get any info for the address");
return; // or exit(1);
}
for (struct addrinfo *r = results; r; r = r->ai_next)
{
char hostname[NI_MAXHOST] = {0};
error = getnameinfo(r->ai_addr, r->ai_addrlen, hostname, sizeof hostname, NULL, 0 , 0);
if (error != 0)
{
continue; // try next one
}
else
{
NSLog (@"Found hostname: %s", hostname);
break;
}
}
freeaddrinfo(results);
There can be multiple names for the address, so you might not want to stop at the first one you find.
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<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
}