linux下使用c++获取MAC和ip地址

  • Post author:
  • Post category:c++
  • Post comments:0评论
#include <iostream>
#include <string>
#include <nl80211.h>
#include <net/if.h>
#include <ifaddrs.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <net/if_arp.h>
#include <netinet/in.h>

// 获取 IP 地址
std::string get_ip_address(const char *ifname) {
    struct ifaddrs *ifaddr, *ifa;
    int family, s, n;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1) {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        if (ifa->ifa_addr == NULL)
            continue;

        family = ifa->ifa_addr->sa_family;

        if (strcmp(ifa->ifa_name, ifname) == 0 && family == AF_INET) {
            s = getnameinfo(ifa->ifa_addr,
                            (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6),
                            host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
            if (s != 0) {
                perror("getnameinfo");
                freeifaddrs(ifaddr);
                exit(EXIT_FAILURE);
            }
            freeifaddrs(ifaddr);
            return std::string(host);
        }
    }

    freeifaddrs(ifaddr);
    return "";
}

// 获取 MAC 地址
std::string get_mac_address(const char *ifname) {
    struct ifreq ifr;
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, ifname, IFNAMSIZ-1);

    ioctl(sockfd, SIOCGIFHWADDR, &ifr);
    close(sockfd);

    char mac[18];
    snprintf(mac, sizeof(mac), "%02x:%02x:%02x:%02x:%02x:%02x",
             (unsigned char) ifr.ifr_hwaddr.sa_data[0],
             (unsigned char) ifr.ifr_hwaddr.sa_data[1],
             (unsigned char) ifr.ifr_hwaddr.sa_data[2],
             (unsigned char) ifr.ifr_hwaddr.sa_data[3],
             (unsigned char) ifr.ifr_hwaddr.sa_data[4],
             (unsigned char) ifr.ifr_hwaddr.sa_data[5]);

    return std::string(mac);
}

int main() {
    std::string ifname = "eth0";
    std::string ip = get_ip_address(ifname.c_str());
    std::string mac = get_mac_address(ifname.c_str());

    std::cout << "IP Address: " << ip << std::endl;
    std::cout << "MAC Address: " << mac << std::endl;

    return 0;
}
文章作者: 张拓
文章链接: http://www.xssl.online/linux%e4%b8%8b%e4%bd%bf%e7%94%a8c%e8%8e%b7%e5%8f%96mac%e5%92%8cip%e5%9c%b0%e5%9d%80/
版权声明: 本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0 许可协议。转载请注明来自 张拓的博客
浏览次数: 326

张拓

陕西西安蓝田张拓QQ1070410059。一生所求不过“心安”二字。 然,尘世多纷扰。

发表回复