获取系统所有IP地址

获取详细网卡信息,请参考ioctl

net/if.h 等相关文件与帮助。

 

 

struct if_nameindex * ifni, *p;
  int fd, numreqs = 30, n, err = -1;
  struct ifconf ifc;
  struct ifreq *ifr;

  if ((fd = socket (AF_INET, SOCK_DGRAM, 0)) < 0){
    perror ("socket");
    exit (1);
  }

  ifc.ifc_buf = NULL;
  for (;;) {
    ifc.ifc_len = sizeof (struct ifreq) * numreqs;
    ifc.ifc_buf = realloc(ifc.ifc_buf, ifc.ifc_len);

    if (ioctl (fd, SIOCGIFCONF, &ifc) < 0) {
      perror ("SIOCGIFCONF");
      goto out;
    }

    if (ifc.ifc_len == sizeof (struct ifreq) *numreqs) {
    /* assume it overflowed and try again */
      numreqs += 10;
      continue;
    }
    break;
  }
  close (fd);

  //uint32_t ip; 
  int i;                                                          
  char ip_str[INET_ADDRSTRLEN];
  ifr = ifc.ifc_req;
  for (i = 0, n = 0; n < ifc.ifc_len; n += sizeof(struct ifreq), i++) {
    /*
    if (getifaddr (AF_INET, ++i, ifr->ifr_name, &ip) == -1){
      perror ("getifaddr failed");
      exit (2);
    }
    */
//ifreq结构已经有了,ip已经存放在里面了
    printf ("Index: %d,/tInterface: %s,/tIP: %s/n", i,
            ifr->ifr_name, inet_ntop (AF_INET, &((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr, ip_str, sizeof (ip_str)));
    ifr++;
  }

 out:
  free(ifc.ifc_buf);

  return 0;

你可能感兴趣的:(struct,socket,null)