获取本地IP

inline uint32_t getLocalIP()
{
  int sock_fd;
  struct ifreq buf[16];
  struct ifconf ifc;
  uint32_t interface_num;
  uint32_t loIp = inet_addr("127.0.0.1");
  uint32_t localIp = 0;
  if((sock_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    return 0;
  ifc.ifc_len = sizeof(buf);
  ifc.ifc_req = buf;
  if(ioctl(sock_fd, SIOCGIFCONF, (char *)&ifc) < 0)
  {
    close(sock_fd);
    return 0;
  }
  interface_num = ifc.ifc_len / sizeof(struct ifreq);
  while(interface_num--) {
    if(ioctl(sock_fd, SIOCGIFFLAGS, (char *)&buf[interface_num]) < 0)
    {
      close(sock_fd);
      return 0;
    }
    if(ioctl(sock_fd, SIOCGIFADDR, (char *)&buf[interface_num]) < 0)
    {
      close(sock_fd);
      return 0;
    }
    if(strcmp(buf[interface_num].ifr_name, "eth0") == 0){
      localIp = (unsigned int ) ( ( ( struct sockaddr_in* ) ( &buf[interface_num].ifr_addr ) )->sin_addr.s_addr );
      if(localIp != loIp)
      {
        close(sock_fd);
        return localIp;
      }
    }
  }
  close(sock_fd);
  return 0;
}

 

你可能感兴趣的:(c++工具类小程序)