美文网首页
获取手机的ip地址

获取手机的ip地址

作者: summer_code | 来源:发表于2017-03-06 09:32 被阅读16次

    之前项目中需要用到获取手机的ip地址 在网上搜集的资料 在这里记录一下:

    首先需要导入系统头文件:





    - (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];

    }

    }

    NSLog(@"deviceIP========%@",deviceIP);

    return deviceIP;

    }

    - (void)viewDidLoad {

    [super viewDidLoad];

    [self getDeviceIPIpAddresses];

    }

    相关文章

      网友评论

          本文标题:获取手机的ip地址

          本文链接:https://www.haomeiwen.com/subject/ceuygttx.html