en2 接口。
添加:
[[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en2"]
到第一个解决方案
iPhone/iPad/OSX: How to get my IP address programmatically?也可以通过有线连接获取设备的IP地址。
更新:只是扩展上面链接的@Raptor 的解决方案;如果两者都存在,这将返回有线和无线 IP 地址。然后只需检查返回字典的值的长度,看看你正在使用什么。
#import <ifaddrs.h>
#import <arpa/inet.h>
+ (NSDictionary *)getBothIPAddresses {
const NSString *WIFI_IF = @"en0";
NSArray *KNOWN_WIRED_IFS = @[@"en1",@"en2",@"en3",@"en4"];
NSArray *KNOWN_CELL_IFS = @[@"pdp_ip0",@"pdp_ip1",@"pdp_ip2",@"pdp_ip3"];
const NSString *UNKNOWN_IP_ADDRESS = @"";
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithDictionary:@{@"wireless":UNKNOWN_IP_ADDRESS,
@"wired":UNKNOWN_IP_ADDRESS,
@"cell":UNKNOWN_IP_ADDRESS}];
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0) {
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL) {
if (temp_addr->ifa_addr == NULL) {
temp_addr = temp_addr->ifa_next;
continue;
}
if(temp_addr->ifa_addr->sa_family == AF_INET) {
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:WIFI_IF]) {
// Get NSString from C String
[addresses setObject:[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] forKey:@"wireless"];
}
// Check if interface is a wired connection
if([KNOWN_WIRED_IFS containsObject:[NSString stringWithUTF8String:temp_addr->ifa_name]]) {
[addresses setObject:[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] forKey:@"wired"];
}
// Check if interface is a cellular connection
if([KNOWN_CELL_IFS containsObject:[NSString stringWithUTF8String:temp_addr->ifa_name]]) {
[addresses setObject:[NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)] forKey:@"cell"];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return addresses;
}
更新:
en3接口,另一种可能;似乎取决于适配器的类型。让我觉得根据所使用的硬件可能还有更多我仍然缺少的接口,所以如果有人发现更多,请发表评论。
更新:
en4 也是;不一定像我最初想的那样依赖于适配器,因为具有所有相同硬件的 Mini 决定从一个接口切换到这个新接口。另外,我开始认为将 ifa_name 与格式为en[2..n] 的任何字符串进行比较可能会更容易,只要它在AF_INET 系列中(例如,en1 不是并且没有' t 返回我们正在寻找的地址);在没有更多证据的情况下为 Prod 实现类似的东西可能还为时过早,所以现在我使用“已知”有线接口列表进行管理。
更新:
也考虑蜂窝AF_INET 接口,在What exactly means iOS networking interface name? what's pdp_ip ? what's ap? 中提到
更新:
以太网 IP 地址最近开始出现在某些新 iPad 上的en1 接口上,因此当它是AF_INET 系列的成员时也应该考虑它。没有明显的韵律或原因,它发生在不同的 iPad 型号和 iOS 版本上。