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

前端 未结 3 1331
醉酒成梦
醉酒成梦 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:02

    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.

提交回复
热议问题