我使用 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];
}
请注意,模拟器适用于 iOS 5 和 iOS 6。只有 iOS 6 设备失败。
gethostbyname() 有什么区别?
或者你有其他解决方案来获取iOS6中的本地ip吗?
有几个possible问题:
- 也许您有一个 IPv6 地址(
gethostbyname()
仅适用于 IPv4),
- 或者从主机名到 IP 地址的名称解析无法正常工作。
以下代码以字符串数组的形式返回所有本地地址。它不依赖于名称解析,并且适用于 IPv4 和 IPv6 地址。
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netdb.h>
// return all local IP addresses
- (NSArray *)localIPAddresses
{
NSMutableArray *ipAddresses = [NSMutableArray array] ;
struct ifaddrs *allInterfaces;
// Get list of all interfaces on the local machine:
if (getifaddrs(&allInterfaces) == 0) {
struct ifaddrs *interface;
// For each interface ...
for (interface = allInterfaces; interface != NULL; interface = interface->ifa_next) {
unsigned int flags = interface->ifa_flags;
struct sockaddr *addr = interface->ifa_addr;
// Check for running IPv4, IPv6 interfaces. Skip the loopback interface.
if ((flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING)) {
if (addr->sa_family == AF_INET || addr->sa_family == AF_INET6) {
// Convert interface address to a human readable string:
char host[NI_MAXHOST];
getnameinfo(addr, addr->sa_len, host, sizeof(host), NULL, 0, NI_NUMERICHOST);
[ipAddresses addObject:[[NSString alloc] initWithUTF8String:host]];
}
}
}
freeifaddrs(allInterfaces);
}
return ipAddresses;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)