获取设备的IP地址,WiFi数据网下皆可。

talk is cheap show u My code


写一个类方法,先导入这几个头文件

.h文件
#import 
#import 
#import 
#import 
@interface getDeviceIPTool : NSObject

+ (NSString *)getDeviceIPipAddress;

@end

.m文件
+ (NSString *)getDeviceIPipAddress{
    
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    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 0) {
            deviceIp = [NSString stringWithFormat:@"%@",ips.lastObject];
        }
    }
    NSLog(@"deviceIP======%@",deviceIp);
    return deviceIp;
}


使用:[类名 getDeviceIPipAddr]; 
                                                      : )

你可能感兴趣的:(获取设备的IP地址,WiFi数据网下皆可。)