iOS 获取内外网ip
Posted JusDoit
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 获取内外网ip相关的知识,希望对你有一定的参考价值。
外网ip 直接访问ip网站即可 https的不知道有什么
#import "IPAddresses.h"
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <arpa/inet.h>
@implementation IPAddresses
+(NSString *)getDeviceIPAddresses //内网静态ip
{
int sockfd = socket(AF_INET,SOCK_DGRAM, 0);
// if (sockfd <</span> 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);
NSString *deviceIP [email protected]"";
for (int i=0; i < ips.count; i++){
if (ips.count >0){
deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
}
}
return deviceIP;
}
//内网ip
+ (NSString *)deviceIPAdress {
NSString *address = @"手机移动网络";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0) {
temp_addr = interfaces;
while (temp_addr != NULL) {
if( (*temp_addr).ifa_addr->sa_family == AF_INET) {
if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
return address;
}
以上是关于iOS 获取内外网ip的主要内容,如果未能解决你的问题,请参考以下文章
第二十九节: Asp.Net Core零散总结(各种目录内外网ip)[不断补充]