小编tar*_*hot的帖子

如何从iOS Objective-C中的ip地址解析主机名

我正在寻找一种方法来解决我的局域网中设备的主机名从其局域网上的IP地址.

我在C中编写了一个程序,它使用gethostbyaddr()函数在Linux上完美运行.

当我在OS X或iOS上尝试它时,它不起作用.

似乎OS X和iOS中的gethostbyaddr()存在问题.

无论如何,如果你有另一个想法从iOS的IP获取远程机器的主机名,它将成为我的一天.

这是我使用的代码:

第一次测试:

192.168.0.101是我们查询主机名的机器的IP地址.

#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>

struct hostent *he;
struct in_addr ipv4addr;
inet_pton(AF_INET, "192.168.0.101", &ipv4addr);
he = gethostbyaddr(&ipv4addr, sizeof ipv4addr, AF_INET);
printf("Host name: %s\n", he->h_name);
Run Code Online (Sandbox Code Playgroud)

这段代码适用于linux,但它不适用于OS X或iOS.

第二次测试:

+ (NSArray *)hostnamesForAddress:(NSString *)address {
    // Get the host reference for the given address.
    struct addrinfo      hints;
    struct addrinfo      *result = NULL;
    memset(&hints, 0, sizeof(hints));
    hints.ai_flags    = AI_NUMERICHOST;
    hints.ai_family   = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_protocol = 0;
    int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], …
Run Code Online (Sandbox Code Playgroud)

objective-c hostname ios

9
推荐指数
1
解决办法
4541
查看次数

标签 统计

hostname ×1

ios ×1

objective-c ×1