Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
[Obj-C]IPアドレス取得コード
#import <ifaddrs.h>
#import <arpa/inet.h>
+ (NSString *)getCellularIPv4Address {
NSString *ip;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *tempAddr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
tempAddr = interfaces;
while (tempAddr != NULL) {
if (tempAddr->ifa_addr->sa_family == AF_INET) { // IPv4
if ([[NSString stringWithUTF8String:tempAddr->ifa_name] isEqualToString:@"pdp_ip0"]) { // Cellular
ip = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) tempAddr->ifa_addr)->sin_addr)];
break;
}
}
tempAddr = tempAddr->ifa_next;
}
}
freeifaddrs(interfaces);
return ip;
}
+ (NSString *)getWiFiIPv4Address {
NSString *ip;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *tempAddr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
tempAddr = interfaces;
while (tempAddr != NULL) {
if (tempAddr->ifa_addr->sa_family == AF_INET) { // IPv4
if ([[NSString stringWithUTF8String:tempAddr->ifa_name] isEqualToString:@"en0"]) { // Wi-Fi
ip = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *) tempAddr->ifa_addr)->sin_addr)];
break;
}
}
tempAddr = tempAddr->ifa_next;
}
}
freeifaddrs(interfaces);
return ip;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment