linux C 獲取ip mac 廣播地址,以及閘道器
阿新 • • 發佈:2019-02-17
獲取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 }
獲取閘道器:
- QString GetGateWay()
- {
- FILE *fp;
- char buf[512];
- char cmd[128];
- char gateway[30];
- char *tmp;
- strcpy(cmd, "ip route");
- fp = popen(cmd, "r");
- if(NULL == fp)
- {
- perror("popen error");
- return"";
- }
- while(fgets(buf, sizeof(buf), fp) != NULL)
- {
- tmp =buf;
- while(*tmp && isspace(*tmp))
- ++ tmp;
- if(strncmp(tmp, "default", strlen("default")) == 0)
- break;
- }
- sscanf(buf, "%*s%*s%s", gateway);
- printf("default gateway:%s/n", gateway);
- pclose(fp);
- return QString(gateway);
- }