#import <ifaddrs.h>
#include <arpa/inet.h>
#include <net/if.h>
//获取IP地址
+(NSDictionary *)getIPAddress{
//无线
NSString *wifilocalIP = @"";
//卡
NSString *simcardlocalIp = @"";
//代理
NSString *agentlocalIp = @"";
BOOL success;
struct ifaddrs * addrs;
const struct ifaddrs * cursor;
NSMutableDictionary *ipTempDic = [NSMutableDictionary dictionary];
//无线
NSString *wifilocalIP = @"";
//卡
NSString *simcardlocalIp = @"";
//代理
NSString *agentlocalIp = @"";
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
// the second test keeps from picking up the loopback address
if (cursor->ifa_addr->sa_family == AF_INET && (cursor->ifa_flags & IFF_LOOPBACK) == 0)
{
NSString *name = [NSString stringWithUTF8String:cursor->ifa_name];
//猜的无线
if ([name isEqualToString:@"en0"] || [name isEqualToString:@"en1"] || [name isEqualToString:@"en2"])
{
wifilocalIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
[ipTempDic setObject:wifilocalIP forKey:@"wifilocalIP"];
//NSLog(@"wifilocalIP:%@",wifilocalIP);
}
//猜的卡
else if ([name isEqualToString:@"pdp_ip0"] || [name isEqualToString:@"pdp_ip1"] || [name isEqualToString:@"pdp_ip2"])
{
simcardlocalIp = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
[ipTempDic setObject:simcardlocalIp forKey:@"simcardlocalIp"];
//NSLog(@"simcardlocalIp:%@",simcardlocalIp);
}
else if ([name isEqualToString:@"ppp0"] || [name isEqualToString:@"ppp01"] || [name isEqualToString:@"ppp02"])
{
agentlocalIp = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)cursor->ifa_addr)->sin_addr)];
[ipTempDic setObject:agentlocalIp forKey:@"agentlocalIp"];
// NSLog(@"agentlocalIp:%@",agentlocalIp);
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
wifilocalIP = [ipTempDic objectForKey:@"wifilocalIP"];
if (wifilocalIP == nil) {
wifilocalIP = @"notfound";
}
simcardlocalIp = [ipTempDic objectForKey:@"simcardlocalIp"];
if (simcardlocalIp == nil) {
simcardlocalIp = @"notfound";
}
agentlocalIp = [ipTempDic objectForKey:@"agentlocalIp"];
if (agentlocalIp == nil) {
agentlocalIp = @"notfound";
}
NSLog(@"获取到的ip地址是*********:%@********",threeIpDic);
return ipTempDic;
}
iOS 获取手机IP 地址
最新推荐文章于 2023-05-04 09:24:18 发布