linux下, 所有的网卡信息写在/proc/net/dev文件,这是个内存映射文件,我们可以从这个文件里面读出网卡名字,然后根据名字利用ioctl函数读出网卡别的信息,比如ip地址,网关,掩码之类的信息。
下面是可运行的代码:
#include <stdio.h>
#include <string.h>#include <errno.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
#include <netinet/in.h>
int get_hwaddr(char *name);
int GetNetCardCount()
{
int nCount = 0;
FILE* f = fopen("/proc/net/dev", "r");
if (!f)
{
fprintf(stderr, "Open /proc/net/dev failed!errno:%d\n", errno);
return nCount;
}
char szLine[512];
fgets(szLine, sizeof(szLine), f); /* eat line */
fgets(szLine, sizeof(szLine), f);
while(fgets(szLine, sizeof(szLine), f))
{
char szName[128] = {0};
sscanf(szLine, "%s", szName);
printf("szline %s\n", szName);
int nLen = strlen(szName);
if (nLen <= 0)continue;
if (szName[nLen - 1] == ':') szName[nLen - 1] = 0;
if (strcmp(szName, "lo") == 0)continue;
nCount++;
get_hwaddr(szName);
}
fclose(f);
f = NULL;
return nCount;
}
/**
* get_hwaddr - get netdevice mac addr
* @name: device name, e.g: eth0
* @hwaddr: where to save mac, 6 byte hwaddr[6]
* @return: 0 on success, -1 on failure
*/
int get_hwaddr(char *name)//, unsigned char *hwaddr)
{
struct ifreq ifr;
unsigned char memzero[6];
unsigned char hwaddr[6];
int sock;
if(name == NULL || hwaddr == NULL){
printf("get_hwaddr: NULL para\n");
return -1;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock < 0){
printf("get_hwaddr: socket error\n");
//return -1;
}
//get eth1 mac addr
memset(hwaddr, 0, 6);
memset(&ifr, 0, sizeof(ifr));
strncpy(ifr.ifr_name, name, 6);
if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0){
perror("get_hwaddr ioctl:");
close(sock);
return -1;
} else {
memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, 6);
printf("hwaddr: %2x : %2x : %2x : %2x : %2x : %2x\n", hwaddr[0], hwaddr[1],hwaddr[2], hwaddr[3],hwaddr[4], hwaddr[5]);
}
memset(memzero, 0, 6);
if(memcmp(memzero, hwaddr, 6) == 0){
printf("no mac\n");
return -1;
}
close(sock);
return 0;
}
int main(int argc, char* argv[])
{
printf("NetCardCount: %d\n", GetNetCardCount());
return 0;
}