linux C 获取ip mac 广播地址,以及网关
获取IP、掩码、MAC获取IP、掩码、MAC和广播地址是比较容易的,只需要调用对应的IOCTL即可。只是大家对Linux下的IOCTL可能不太熟悉。却看示例代码: constchar* szDevName = ”eth0“ (网卡名称)0001 void DispNetInfo(const char* szDevName)0002 {0003 int s
·
获取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);
- }
更多推荐
已为社区贡献1条内容
所有评论(0)