栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

如何获取LINUX主机所有的IP

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何获取LINUX主机所有的IP

上个月写了一篇文章,介绍了如何获取本机的第一个IP。后面我再想是否有办法获取LINUX主机的所有的IP,通过查询资料,找到了方法。

借助对象ifaddrs以及getifaddrs函数可以实现这样的功能。

     

#include 
#include 
#include 
#include 
#include 
#include 
#include 
int main()
{
  char hostname[100]={0};
  char localIpAddress[256]={0};
  struct hostent *h;
  gethostname(hostname,sizeof(hostname));
  printf("host name is %s n",hostname);
  h=gethostbyname(hostname);
  //struct in_addr *temp;
  //temp=(struct in_addr *)h->h_addr;
  //strcpy(localIpAddress,inet_ntoa(*temp));
  //printf("first ip is %sn",localIpAddress);
  char mac[30]={0};
  struct ifaddrs * ifhead=NULL;
  struct ifaddrs * ifpoint=NULL;
  struct in_addr * intmpAddrPtr=NULL;
  getifaddrs(&ifhead);
  ifpoint=ifhead;
  while(ifpoint!=NULL)
  {
    if(ifpoint->ifa_addr->sa_family==AF_INET)
    {
       intmpAddrPtr=&((struct sockaddr_in *)ifpoint->ifa_addr)->sin_addr;
       char addressBuffer[INET_ADDRSTRLEN];
       inet_ntop(AF_INET, intmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
       printf("%s IPv4: %sn", ifpoint->ifa_name, addressBuffer);
    }
    else if(ifpoint->ifa_addr->sa_family==AF_INET6)
    {
      intmpAddrPtr=&((struct sockaddr_in *)ifpoint->ifa_addr)->sin_addr;
      char addressBuffer[INET6_ADDRSTRLEN];
      inet_ntop(AF_INET6, intmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
      printf("%s IPv6: %sn", ifpoint->ifa_name, addressBuffer); 
    }
     ifpoint=ifpoint->ifa_next;
  }
  if (ifhead) 
  {
       freeifaddrs(ifhead); 
       ifhead = NULL; 
  }
}

其中通过ifpoint=ifpoint->ifa_next;可以实现对主机IP的遍历查看。通过intmpAddrPtr=&((struct sockaddr_in *)ifpoint->ifa_addr)->sin_addr;可以获取到in_addr的指针。通过函数inet_ntop可以将16进制的IP地址转成字符形式的XX.XX.XX.XX这样的形式展示。

编译及运行实例代码如下:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/730212.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号