views:

56

answers:

1

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 get the IPAddress from a domain name. Is it possible in objective c ? How ?

The second question is How to get the name of device/machine by using it's IPAddress. Say for example I have an ipAddress 192.168.0.74 = What is the device name ? in Objective c ? How ?

Thanks in advance for sharing your knowledge.

A: 

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.

dreamlax