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

获取网卡名称和网卡MAC地址

程序员文章站 2022-06-05 22:04:21
...

test.h

#ifndef TEST_H
#define TEST_H

#include <map>
#include <string>

class MacAddress {
public:
    int GetMacNameAddress(std::map<std::string, std::string>& mac);

private:
    void GetMacName();
    int GetMacAddress(std::string name);
    std::map<std::string, std::string> mMac;
};

#endif

test.cpp

#include "test.h"
#include <iostream>
#include <ifaddrs.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <net/if.h>

using namespace std;

int MacAddress::GetMacNameAddress(map<string, string>& mac)
{
    GetMacName();
    auto iter = mMac.begin();
    while (iter != mMac.end()) {
        cout << "key:" << iter->first << " " << "value:" << iter->second << endl;
        int ret = GetMacAddress(iter->first);
        if (ret != 0) {
            cout << "GetMacAddress Failed!" << endl;
            return -1;
        } 
        if (iter->second == "00 00 00 00 00 00") {
            cout << "erase key:" << iter->first << " " << "value:" << iter->second << endl;
            iter = mMac.erase(iter);
        } else {
            iter++;
        }
    }
    mac = mMac;
    return 0;
}

void MacAddress::GetMacName()
{
    cout << "GetMacName Start>>>" << endl;

    struct ifaddrs * ifAddrStruct = nullptr; 
    void * tmpAddrPtr = nullptr;
    getifaddrs(&ifAddrStruct);
    while (ifAddrStruct != nullptr) {
        cout << "ifa_name:" << ifAddrStruct->ifa_name << endl;
        mMac.insert(make_pair(ifAddrStruct->ifa_name, ""));
        ifAddrStruct = ifAddrStruct->ifa_next;
    }

    cout << "GetMacName End<<<" << endl;
}


int MacAddress::GetMacAddress(string name)
{
    cout << "GetMacAddress Start>>>" << endl;

    struct ifreq ifreq;
    char mac[32] = "";

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0)
    {
        cout << "error sock" << endl;
        return -1;
    }
    strcpy(ifreq.ifr_name, name.c_str());
    if(ioctl(sock,SIOCGIFHWADDR,&ifreq) < 0)
    {
        cout << "error ioctl" << endl;
        return -1;
    }
    for(int i = 0; i < 6; i++){
        sprintf(mac+3*i, "%02X ", (unsigned char)ifreq.ifr_hwaddr.sa_data[i]);
    }
    mac[strlen(mac) - 1] = 0;
    cout << "MAC: " << mac << endl;
    mMac[name] = mac;

    cout << "GetMacAddress End<<<" << endl;
    return 0;
}

main.cpp

#include "test.h"
#include <iostream>

using namespace std;

int main()
{
    MacAddress *macAddress = new MacAddress();
    map<string, string> mac;
    macAddress->GetMacNameAddress(mac);

    cout << "main debug: =========================" << endl;
    auto iter = mac.begin();
    while (iter != mac.end()) {
        cout << "key:" << iter->first << " " << "value:" << iter->second << endl;
        iter++;
    }

    delete macAddress;
    return 0;
}

build.sh

#!/bin/bash

g++ test.cpp main.cpp -o test -g -std=c++14