我正在制作一个 iPhone 应用程序,我需要将主机名字符串解析为 IP 地址字符串。例如,“MyComputer.local”->“192.168.0.7”。我试过做一些事情,但都没有奏效。这是我现在拥有的:
struct hostent *hostentry;
hostentry = gethostbyname("MyComputer.local");
char *ipbuf = NULL;
inet_ntop(AF_INET, hostentry->h_addr_list[0], ipbuf, hostentry->h_length);
ipAddress = [NSString stringWithFormat:@"%s" , ipbuf];
出于某种原因,它总是在 inet_ntop 上崩溃,是的,我正在使用现有的主机名进行测试。谢谢!
最佳答案
代替 inet_ntop
试试 inet_ntoa
。
它有助于将复合语句分解一点:
struct hostent *hostentry;
hostentry = gethostbyname("zaph.com");
NSLog(@"name: %s", hostentry->h_name);
struct in_addr **addr_list;
addr_list = (struct in_addr **)hostentry->h_addr_list;
char* ipAddr = inet_ntoa(*addr_list[0]);
NSString *ipAddress = [NSString stringWithFormat:@"%s", ipAddr];
NSLog(@"ipAddress: %@", ipAddress);
输出:
name: zaph.com
ipAddress: 72.35.89.108
关于ios - 将主机名字符串解析为 IP 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28204094/