私はこれを成功させて試しました私はそれがあなたに役立つことを願っています
+(NSString *)getIpLocally:(NSString *)networkInterface ipVersion:(int)ipVersion
{
if(ipVersion != 4 && ipVersion != 6)
{
NSLog(@"getIpLocally unknown version of IP: %i",ipVersion);
return nil;
}
NSString *networkInterfaceRef;
if ([networkInterface isEqualToString:@"ios_cellular"])
{
networkInterfaceRef = @"pdp_ip0";
}
else if([networkInterface isEqualToString:@"ios_wifi"])
{
networkInterfaceRef = @"en0"; //en1 on simulator if mac on wifi
}
else
{
NSLog(@"getIpLocally unknown interface: %@",networkInterface);
return nil;
}
NSString *address = nil;
struct ifaddrs *addrs = NULL;
struct ifaddrs *cursor = NULL;
struct sockaddr_in *s4;
struct sockaddr_in6 *s6;
char buf[64];
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&addrs);
if (success == 0)
{
// Loop through linked list of interfaces
cursor = addrs;
while(cursor != NULL)
{
if((ipVersion == 4 && cursor->ifa_addr->sa_family == AF_INET) ||
(ipVersion == 6 && cursor->ifa_addr->sa_family == AF_INET6))
{
NSLog(@"Network Interface: %@",[NSString stringWithUTF8String:cursor->ifa_name]);
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:cursor->ifa_name] isEqualToString:networkInterfaceRef])
{
if(ipVersion == 4)
{
s4 = (struct sockaddr_in *)cursor->ifa_addr;
if (inet_ntop(cursor->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, sizeof(buf)) == NULL)
{
NSLog(@"%s: inet_ntop failed for v4!\n",cursor->ifa_name);
}
else{
address = [NSString stringWithUTF8String:buf];
}
}
if (ipVersion == 6)
{
s6 = (struct sockaddr_in6 *)(cursor->ifa_addr);
if (inet_ntop(cursor->ifa_addr->sa_family, (void *)&(s6->sin6_addr), buf, sizeof(buf)) == NULL)
{
NSLog(@"%s: inet_ntop failed for v6!\n",cursor->ifa_name);
}
else{
address = [NSString stringWithUTF8String:buf];
}
}
}
}
cursor = cursor->ifa_next;
}
}
// Free memory
freeifaddrs(addrs);
return address;
}
使用できるIPアドレスを表示するには:
NSLog(@"ip v4: %@",[NSString getIpLocally:@"ios_cellular" ipVersion:4]);