获取IP、掩码、MAC

获取IP、掩码、MAC和广播地址是比较容易的,只需要调用对应的IOCTL即可。只是大家对Linux下的IOCTL可能不太熟悉。却看示例代码:

 const char* szDevName  =  ”eth0“   (网卡名称)

0001 void DispNetInfo(const char* szDevName)
0002 {
0003     int s = socket(AF_INET, SOCK_DGRAM, 0);
0004     if (s < 0)
0005     {
0006         fprintf(stderr, "Create socket failed!errno=%d", errno);
0007         return;
0008     }
0009 
0010     struct ifreq ifr;
0011     unsigned char mac[6];
0012     unsigned long nIP, nNetmask, nBroadIP;
0013 
0014     printf("%s:\n", szDevName);
0015 
0016     strcpy(ifr.ifr_name, szDevName);
0017     if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
0018     {
0019         return;
0020     }
0021     memcpy(mac, ifr.ifr_hwaddr.sa_data, sizeof(mac));
0022     printf("\tMAC: %02x-%02x-%02x-%02x-%02x-%02x\n",
0023             mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
0024 
0025     strcpy(ifr.ifr_name, szDevName);
0026     if (ioctl(s, SIOCGIFADDR, &ifr) < 0)
0027     {
0028         nIP = 0;
0029     }
0030     else
0031     {
0032         nIP = *(unsigned long*)&ifr.ifr_broadaddr.sa_data[2];
0033     }
0034     printf("\tIP: %s\n", inet_ntoa(*(in_addr*)&nIP));
0035 
0036     strcpy(ifr.ifr_name, szDevName);
0037     if (ioctl(s, SIOCGIFBRDADDR, &ifr) < 0)
0038     {
0039         nBroadIP = 0;
0040     }
0041     else
0042     {
0043         nBroadIP = *(unsigned long*)&ifr.ifr_broadaddr.sa_data[2];
0044     }
0045     printf("\tBroadIP: %s\n", inet_ntoa(*(in_addr*)&nBroadIP));
0046 
0047     strcpy(ifr.ifr_name, szDevName);
0048     if (ioctl(s, SIOCGIFNETMASK, &ifr) < 0)
0049     {
0050         nNetmask = 0;
0051     }
0052     else
0053     {
0054         nNetmask = *(unsigned long*)&ifr.ifr_netmask.sa_data[2];
0055     }
0056     printf("\tNetmask: %s\n", inet_ntoa(*(in_addr*)&nNetmask));
0057     close(s);
0058 }

 

获取网关:

 

  1. QString GetGateWay()  
  2. {  
  3.     FILE *fp;  
  4.     char buf[512];  
  5.     char cmd[128];  
  6.     char gateway[30];  
  7.     char *tmp;  
  8.   
  9.     strcpy(cmd, "ip route");  
  10.     fp = popen(cmd, "r");  
  11.     if(NULL == fp)  
  12.     {  
  13.         perror("popen error");  
  14.         return "";  
  15.     }  
  16.     while(fgets(buf, sizeof(buf), fp) != NULL)  
  17.     {  
  18.         tmp =buf;  
  19.         while(*tmp && isspace(*tmp))  
  20.             ++ tmp;  
  21.         if(strncmp(tmp, "default", strlen("default")) == 0)  
  22.             break;  
  23.     }  
  24.     sscanf(buf, "%*s%*s%s", gateway);         
  25.     printf("default gateway:%s/n", gateway);  
  26.     pclose(fp);  
  27.       
  28.     return QString(gateway);  
  29. }  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Logo

更多推荐