1

如何从 iOS 上的给定主机名获取 IP?

我试过谷歌但一无所获。

4

1 回答 1

9

以下代码适用于 IPv4 和 IPv6。它用于getaddrinfo()检索主机的 IP 地址列表,getnameinfo()并将每个 IP 地址转换为字符串。(为简洁起见,省略了错误检查。)

struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;        // PF_INET if you want only IPv4 addresses
hints.ai_protocol = IPPROTO_TCP;

struct addrinfo *addrs, *addr;

getaddrinfo("www.google.com", NULL, &hints, &addrs);
for (addr = addrs; addr; addr = addr->ai_next) {

    char host[NI_MAXHOST];
    getnameinfo(addr->ai_addr, addr->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
    printf("%s\n", host);

}
freeaddrinfo(addrs);
于 2013-08-20T21:06:08.047 回答