获取Linux网卡信息

代码示例获取网卡信息。

通过命令获取

  • ARP(Address Resolution Protocol)地址解析协议。
  • 执行cat /proc/net/arp得到以下信息:
    1
    2
    3
    4
    ubuntu:~$ cat /proc/net/arp
    IP address HW type Flags HW address Mask Device
    192.168.72.2 0x1 0x2 00:50:56:f4:70:28 * ens33
    192.168.72.254 0x1 0x2 00:50:56:ed:51:f7 * ens33

其中,HW type硬件类型

类型
0x01 ether (Ethernet)
0xf dlci (Frame Relay DLCI)
0x17 strip (Metricom Starmode IP)

通过代码获取

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <list>

using namespace std;

struct NetworkInfo {
string deviceName;
string ip;
string mask;
int hardwareType; /* 硬件类型 */
string macAddress;
};

list<NetworkInfo> getAllNetworkInfo()
{
list<NetworkInfo> result;
char buf[128] = {0};

FILE *fp = fopen("/proc/net/arp", "r");
if (fp == NULL)
return result;

/* 移除第一行无关内容 */
if (fgets(buf, sizeof(buf), fp) == NULL)
return result;

memset(buf, 0, sizeof(buf)); // 重置缓冲区
while(fgets(buf, sizeof(buf), fp) != NULL) {

char ip[16] = {0};
char macAddress[32] = {0};
char mask[16] = {0};
char deviceName[512] = {0};
int hardwareType = 0;
int flags = 0;
/* 读数据 */
sscanf(buf, "%s 0x%x 0x%x %s %s %s\n",
ip,
&hardwareType,
&flags,
macAddress,
mask,
deviceName);

/* 装载数据 */
NetworkInfo info;
info.deviceName = deviceName;
info.ip = ip;
info.mask = mask;
info.hardwareType = hardwareType;
info.macAddress = macAddress;

result.push_back(info);

memset(buf, 0, sizeof(buf)); // 重置缓冲区
}

fclose(fp);

return result;
}