如何从Objective C中的域名获取IP地址和IP地址的域名?

问题描述:

我可以通过使用此问题的答案获取我正在使用的设备/机器的当前IP地址。

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

我已经通过了这个问题。 Java允许从域名获取IP地址。在Objective C中有可能吗?如何?

I have gone through this question. Java allows to get the IP address from a domain name. Is it possible in Objective C? How?

第二个问题是如何使用其IP地址获取设备/机器的名称。比方说我有一个IP地址192.168.0.74 =什么是设备名称?目标C?

The second question is How to get the name of device/machine by using its IP address. Say for example I have an IP address 192.168.0.74 = What is the device name? in Objective C?

我不确定这是否是最好的方法,但它对我有用,大多。我输入了StackOverflow的IP地址(69.59.196.211),它给了我 stackoverflow.com ,但我输入了谷歌的一个IP地址(210.55.180.158),它给了我回来了 cache.googlevideo.com (对于所有结果,而不仅仅是第一个结果)。

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.