iOS开发下获取设备的网络ip地址

2016-03-31  本文已影响0人  忆风_

一、导入

#import  <sys/socket.h>

#import  <sys/sockio.h>

#import  <sys/ioctl.h>

#import  <net/if.h>

#import  <arpa/inet.h>

二、调用函数方法

例如:NSString*deviceIP_01 = [selfgetDeviceIPIpAddresses];

         NLLog(@"deviceIP_01: %@",deviceIP_01);

- (NSString*)getDeviceIPIpAddresses

{

intsockfd =socket(AF_INET,SOCK_DGRAM,0);

// if (sockfd < 0) return nil;

NSMutableArray*ips = [NSMutableArrayarray];

intBUFFERSIZE =4096;

structifconfifc;

charbuffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;

structifreq*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 = (structifreq*)ptr;

intlen =sizeof(structsockaddr);

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 = [NSStringstringWithFormat:@"%s",inet_ntoa(((structsockaddr_in*)&ifr->ifr_addr)->sin_addr)];

[ipsaddObject:ip];

}

}

close(sockfd);

NSString*deviceIP =@"";

for(inti=0; i < ips.count; i++)

{

if(ips.count>0)

{

deviceIP = [NSStringstringWithFormat:@"%@",ips.lastObject];

}

}

returndeviceIP;

}

上一篇 下一篇

猜你喜欢

热点阅读