ios下获取设备的IP地址

要获取设备的IP地址,网上随便一搜就能找到一大堆结果,但是这些能找到的代码基本上都是用C写的,并没有针对iOS做过优化调整,使用起来也不方便。就只是要获取IP地址而已,封装成一个函数调用一下然后使用起来才方便。代码比较简单,就是把网上抄来的代码做了整理和iOS适配。函数返回一个包含了所有网卡的IP地址的一个数组。

- (NSArray *)getIpAddresses {
  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);
  return ips;
}

文件头部需要加上这些import

#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
This entry was posted in iOS. Bookmark the permalink.

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Verify Code   If you cannot see the CheckCode image,please refresh the page again!