欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

获取Linux网卡信息

程序员文章站 2022-06-03 08:46:06
...

代码示例获取网卡信息。

通过命令获取

  • ARP(Address Resolution Protocol)地址解析协议。
  • 执行cat /proc/net/arp得到以下信息:
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)

通过代码获取

#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;
}