我使用gethostbyname()来获取设备IP.在iOS5中,它运行良好.但在iOS6中,gethostbyname()返回的主机值为NULL.下面是我获取设备当前本地IP的代码.
// retun the host name
- (NSString *)hostname
{
char baseHostName[256];
int success = gethostname(baseHostName, 255);
if (success != 0) return nil;
baseHostName[255] = '\0';
#if !TARGET_IPHONE_SIMULATOR
return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}
// return IP Address
- (NSString *)localIPAddress
{
struct hostent *host = gethostbyname([[self hostname] UTF8String]);
if (!host) {
herror("resolv");
return nil;
}
struct in_addr **list = (struct in_addr **)host->h_addr_list;
return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}
Run Code Online (Sandbox Code Playgroud)
请注意,模拟器适用于iOS5和iOS6.只有iOS6设备失败.gethostbyname()有什么区别?或者你有任何其他解决方案来获得iOS6中的本地IP?