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

talk is cheap show u My code


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

.h文件
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
@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<ips.count; i++) {
        if (ips.count > 0) {
            deviceIp = [NSString stringWithFormat:@"%@",ips.lastObject];
        }
    }
    NSLog(@"deviceIP======%@",deviceIp);
    return deviceIp;
}


使用:[类名 getDeviceIPipAddr]; 
                                                      : )
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,856评论 25 709
  • 最近我在想,如果没来北京,我现在会是怎样一个人。 大概会在北方小城里谋一份体制内的工作,上班受小气,下班喝大酒,停...
    小贤君阅读 3,443评论 2 3
  • 想你的時候是真的好想你,甚至都忘了你怎麼傷害我的。也許,你到底是個什麼樣的人對我不重要,重要的是你總能引起我的感覺...
    昕再阅读 1,527评论 0 0
  • 文 | 卿卿子衿 昨夜寒风吹乍起,杏雨润湿庭中荷。 桂酒盈香沁满园,欲攀蟾宫赠姮娥。 END.
    柳子卿阅读 2,187评论 0 1