ios - 将主机名字符串解析为 IP 字符串

标签 ios objective-c

我正在制作一个 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/

相关文章:

ios - 实例化另一个 View Controller 时如何传递数据

ios - 在导航 Controller 中的 View 之间跳转

objective-c - 使用 NSImages 设置背景颜色?

iphone - 如何在 iOS 中最有效和高效地存储数据,尤其是存储便签实例

iPhone:仅将 UITableView 的一部分置于编辑模式

iphone - NSOperation 中显示的 UIAlertView - View Controller 无响应

iphone - ios 身份验证的最佳实践和教程

ios - 两个类之间的弱变量和指针问题

iphone - 回收单元格时的 UITableView 单元格布局

objective-c - UIView背景图像不旋转