以前做過獲取設(shè)備IP地址的功能巍沙,但是由于當(dāng)時(shí)代碼管理不當(dāng)犯祠,很多代碼已經(jīng)遺失,現(xiàn)在只能重新過一遍窖铡,也讓自己更有基情激情的學(xué)習(xí)疗锐。網(wǎng)上關(guān)于這方面的文章很多,但是找到自己真正需要的卻不容易费彼,經(jīng)過幾番周折窒悔。終于在著名的stackoverflow上面找到了我想要的答案。
代碼如下:(最新代碼敌买,請(qǐng)往下翻)
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
#pragma mark - 獲取設(shè)備當(dāng)前本地IP地址
+ (NSString *)getIPAddress:(BOOL)preferIPv4
{
NSArray *searchArray = preferIPv4 ?
@[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self getIPAddresses];
NSLog(@"addresses: %@", addresses);
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
address = addresses[key];
//篩選出IP地址格式
if([self isValidatIP:address]) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
+ (BOOL)isValidatIP:(NSString *)ipAddress {
if (ipAddress.length == 0) {
return NO;
}
NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
NSString *result=[ipAddress substringWithRange:resultRange];
//輸出結(jié)果
NSLog(@"%@",result);
return YES;
}
}
return NO;
}
+ (NSDictionary *)getIPAddresses
{
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
2017年01月11日
很多朋友說(shuō)這個(gè)方法只能獲取到內(nèi)網(wǎng)IP简珠,無(wú)法獲取公網(wǎng)IP,確實(shí)虹钮,這邊補(bǔ)充下獲取公網(wǎng)IP方式聋庵。(由于訪問網(wǎng)絡(luò)緩慢,最新做法請(qǐng)往下翻)
//方法一:
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://ifconfig.me/ip"];
NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
//方法二:個(gè)人推薦用這個(gè)請(qǐng)求芙粱,速度比較快
/*
http://ipof.in/json
http://ipof.in/xml
http://ipof.in/txt
If you want HTTPS you can use the same URLs with https prefix. The advantage being that even if you are on a Wifi you will get the public address.
*/
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://ipof.in/txt"];
NSString *ip = [NSString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
2017年08月04日
增加部分公開API
1祭玉、淘寶API
1. 請(qǐng)求接口(GET):
查詢某ip信息:http://ip.taobao.com/service/getIpInfo.php?ip=ip地址
查詢自己的ip信息:http://ip.taobao.com/service/getIpInfo.php?ip=myip
2. 響應(yīng)信息:
(json格式的)國(guó)家 、蚀号稀(自治區(qū)或直轄市)脱货、市(縣)、運(yùn)營(yíng)商
3. 返回?cái)?shù)據(jù)格式:
{
"code": 0,
"data": {
"country": "中國(guó)",
"country_id": "CN",
"area": "華南",
"area_id": "800000",
"region": "廣東省",
"region_id": "440000",
"city": "深圳市",
"city_id": "440300",
"county": "",
"county_id": "-1",
"isp": "電信",
"isp_id": "100017",
"ip": "121.35.211.41"
}
}
其中code的值的含義為律姨,0:成功振峻,1:失敗。
4. 訪問限制:為了保障服務(wù)正常運(yùn)行择份,每個(gè)用戶的訪問頻率需小于10qps扣孟。
參數(shù)名 | 含義 |
---|---|
code | 狀態(tài)碼,正常為0荣赶,異常的時(shí)候?yàn)榉?凤价。 |
data | 查詢到的結(jié)果鸽斟。 |
country | 國(guó)家。 |
country_id | 國(guó)家代碼利诺。 |
area | 地區(qū)名稱(華南富蓄、華北...)。 |
area_id | 地區(qū)編號(hào)慢逾。 |
region | 省名稱格粪。 |
region_id | 省編號(hào)。 |
city | 市名稱氛改。 |
city_id | 市編號(hào)。 |
county | 縣名稱比伏。 |
county_id | 縣編號(hào)胜卤。 |
isp | ISP服務(wù)商名稱(電信/聯(lián)通/鐵通/移動(dòng)...)。 |
isp_id | ISP服務(wù)商編號(hào)赁项。 |
ip | 查詢的IP地址葛躏。 |
2、站長(zhǎng)工具API
http://ip.chinaz.com/getip.aspx
返回?cái)?shù)據(jù)格式:
{ip:'121.35.211.41',address:'廣東省深圳市 電信'}
2017年11月17日
今天將上面的資料整一塊整理下悠菜,由于獲取ip地址的需求有很多舰攒,有的需要內(nèi)網(wǎng)ip,有的需要外網(wǎng)ip悔醋,這里全部整理一下摩窃。之前上面使用的獲取外網(wǎng)ip的方式請(qǐng)求緩慢,這邊替換成最新的方式芬骄。也比較適合國(guó)內(nèi)用戶猾愿。
#import <ifaddrs.h>
#import <arpa/inet.h>
#import <net/if.h>
#define IOS_CELLULAR @"pdp_ip0"
#define IOS_WIFI @"en0"
#define IOS_VPN @"utun0"
#define IP_ADDR_IPv4 @"ipv4"
#define IP_ADDR_IPv6 @"ipv6"
#pragma mark - 獲取設(shè)備當(dāng)前網(wǎng)絡(luò)IP地址
+ (NSString *)getNetworkIPAddress {
//方式一:淘寶api
NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
NSData *data = [NSData dataWithContentsOfURL:ipURL];
NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *ipStr = nil;
if (ipDic && [ipDic[@"code"] integerValue] == 0) {
//獲取成功
ipStr = ipDic[@"data"][@"ip"];
}
return (ipStr ? ipStr : @"0.0.0.0");
//方式二:新浪api
NSError *error;
NSURL *ipURL = [NSURL URLWithString:@"http://pv.sohu.com/cityjson?ie=utf-8"];
NSMutableString *ip = [NSMutableString stringWithContentsOfURL:ipURL encoding:NSUTF8StringEncoding error:&error];
//判斷返回字符串是否為所需數(shù)據(jù)
if ([ip hasPrefix:@"var returnCitySN = "]) {
//對(duì)字符串進(jìn)行處理,然后進(jìn)行json解析
//刪除字符串多余字符串
NSRange range = NSMakeRange(0, 19);
[ip deleteCharactersInRange:range];
NSString * nowIp =[ip substringToIndex:ip.length-1];
//將字符串轉(zhuǎn)換成二進(jìn)制進(jìn)行Json解析
NSData * data = [nowIp dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"%@",dict);
return dict[@"cip"] ? dict[@"cip"] : @"0.0.0.0";
}
return @"0.0.0.0";
}
#pragma mark - 獲取設(shè)備當(dāng)前本地IP地址
+ (NSString *)getLocalIPAddress:(BOOL)preferIPv4 {
NSArray *searchArray = preferIPv4 ?
@[ IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
@[ IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
NSDictionary *addresses = [self getIPAddresses];
NSLog(@"addresses: %@", addresses);
__block NSString *address;
[searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL *stop) {
address = addresses[key];
//篩選出IP地址格式
if([self isValidatIP:address]) *stop = YES;
} ];
return address ? address : @"0.0.0.0";
}
+ (BOOL)isValidatIP:(NSString *)ipAddress {
if (ipAddress.length == 0) {
return NO;
}
NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
if (regex != nil) {
NSTextCheckingResult *firstMatch=[regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
if (firstMatch) {
NSRange resultRange = [firstMatch rangeAtIndex:0];
NSString *result=[ipAddress substringWithRange:resultRange];
//輸出結(jié)果
NSLog(@"%@",result);
return YES;
}
}
return NO;
}
+ (NSDictionary *)getIPAddresses {
NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
// retrieve the current interfaces - returns 0 on success
struct ifaddrs *interfaces;
if(!getifaddrs(&interfaces)) {
// Loop through linked list of interfaces
struct ifaddrs *interface;
for(interface=interfaces; interface; interface=interface->ifa_next) {
if(!(interface->ifa_flags & IFF_UP) /* || (interface->ifa_flags & IFF_LOOPBACK) */ ) {
continue; // deeply nested code harder to read
}
const struct sockaddr_in *addr = (const struct sockaddr_in*)interface->ifa_addr;
char addrBuf[ MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) ];
if(addr && (addr->sin_family==AF_INET || addr->sin_family==AF_INET6)) {
NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
NSString *type;
if(addr->sin_family == AF_INET) {
if(inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
type = IP_ADDR_IPv4;
}
} else {
const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6*)interface->ifa_addr;
if(inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
type = IP_ADDR_IPv6;
}
}
if(type) {
NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
addresses[key] = [NSString stringWithUTF8String:addrBuf];
}
}
}
// Free memory
freeifaddrs(interfaces);
}
return [addresses count] ? addresses : nil;
}
再一次感謝您花費(fèi)時(shí)間閱讀這篇文章账阻!
微博: @Danny_呂昌輝
博客: SuperDanny