获取局域网ip的方式:
1、实现方法:
+ (NSString *)getIpAddresses {
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) return nil;
NSMutableArray *ips = [NSMutableArray array];
int BUFFERSIZE = 4096;
struct ifconf ifc;
char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
struct ifreq *ifr, ifrcopy;
ifc.ifc_len = BUFFERSIZE;
ifc.ifc_buf = buffer;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) >= 0){
for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
ifr = (struct ifreq *)ptr;
int len = sizeof(struct sockaddr);
if (ifr->ifr_addr.sa_len > len) {
len = ifr->ifr_addr.sa_len;
}
ptr += sizeof(ifr->ifr_name) + len;
if (ifr->ifr_addr.sa_family != AF_INET) continue;
if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL) *cptr = 0;
if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) continue;
memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
ifrcopy = *ifr;
ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
if ((ifrcopy.ifr_flags & IFF_UP) == 0) continue;
NSString *ip = [NSString stringWithFormat:@"%s", inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
[ips addObject:ip];
}
}
close(sockfd);
return [ips lastObject];
}
调用:获取局域网的IP
[JXGetUserIP getIpAddresses]
获取外网的IP的方法
-(void)urlRequestOperation{
//http://psy-api.shzenon.cn/
//http://ip.taobao.com/service/getIpInfo.php?ip=myip
NSString *URLTmp = @"http://psy-api.shzenon.cn?ip=myip";
NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; //转码成UTF-8 否则可能会出现错误
// [URLTmp stringByAddingPercentEncodingWithAllowedCharacters:(nonnull NSCharacterSet *)]
URLTmp = URLTmp1;
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:
^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"Success: %@", operation.responseString);
NSString *requestTmp = [NSString stringWithString:operation.responseString];
NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
//系统自带JSON解析
NSDictionary *resultDic =
[NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"aaaaaaa=====%@",resultDic);
UILabel * label1 =
[[UILabel alloc]initWithFrame:CGRectMake(100, 20, 200, 30)];
label1.backgroundColor = [UIColor yellowColor];
label1.text = [[resultDic objectForKey:@"data"] objectForKey:@"ip"];
[self.view addSubview:label1];
UILabel * label2 = [[UILabel alloc]initWithFrame:CGRectMake(100, 70, 200, 30)];
label2.backgroundColor = [UIColor yellowColor];
label2.text = [[resultDic objectForKey:@"data"] objectForKey:@"city"];
[self.view addSubview:label2];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
[operation start];
}
github下载地址:https://github.com/fenglingdeyi/IP