1. 程式人生 > >linux C 獲取ip mac 廣播地址,以及閘道器

linux C 獲取ip mac 廣播地址,以及閘道器

獲取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.     strcpy(cmd, "ip route");  
  9.     fp = popen(cmd, "r");  
  10.     if(NULL == fp)  
  11.     {  
  12.         perror("popen error");  
  13.         return"";  
  14.     }  
  15.     while(fgets(buf, sizeof(buf), fp) != NULL)  
  16.     {  
  17.         tmp =buf;  
  18.         while(*tmp && isspace(*tmp))  
  19.             ++ tmp;  
  20.         if(strncmp(tmp, "default", strlen("default")) == 0)  
  21.             break;  
  22.     }  
  23.     sscanf(buf, "%*s%*s%s", gateway);         
  24.     printf("default gateway:%s/n", gateway);  
  25.     pclose(fp);  
  26.     return QString(gateway);  
  27. }