iOS获取设备IP地址
2016-04-05 17:33
351 查看
WIFI环境下获取IP地址:
#import <ifaddrs.h>
#import <arpa/inet.h>
// Get IP Address - (NSString *)getIPAddress { NSString *address = @"error"; 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->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:@"en0"]) { // Get NSString from C String address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; } } temp_addr = temp_addr->ifa_next; } } // Free memory freeifaddrs(interfaces); return address;}
--------------------------------------------------
有WIFI或者流量情况下获取IP地址:
#import <sys/socket.h> #import <sys/sockio.h> #import <sys/ioctl.h> #import <net/if.h> #import <arpa/inet.h>
- (NSString *)getDeviceIPIpAddresses { 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); NSString *deviceIP = @""; for (int i=0; i < ips.count; i++) { if (ips.count > 0) { deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject]; } } return deviceIP; }
相关文章推荐
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 峰回路转,Firefox 浏览器即将重返 iOS 平台
- 不可修补的 iOS 漏洞可能导致 iPhone 4s 到 iPhone X 永久越狱
- iOS 12.4 系统遭黑客破解,漏洞危及数百万用户
- 每日安全资讯:NSO,一家专业入侵 iPhone 的神秘公司
- [转][源代码]Comex公布JailbreakMe 3.0源代码
- dns。dhcp,ftp
- C# IP地址与整数之间转换的具体方法
- SQL语句实现查询SQL Server服务器名称和IP地址
- 可以获取客户端的IP地址的sql语句
- C#如何自动选择出系统中最合适的IP地址
- vc获取计算机名和ip地址的方法
- C#使用有道ip地址查询接口方法实例详解
- js针对ip地址、子网掩码、网关的逻辑性判断
- JS不能跨域借助jquery获取IP地址的方法
- PHP中根据IP地址判断城市实现城市切换或跳转代码
- 腾讯与新浪的通过IP地址获取当前地理位置(省份)的接口
- javascript将ip地址第四段用星号代替的两种方法
- IP地址与整数之间的转换实现代码(asp.net)