#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;
}
本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0 许可协议。转载请注明来自 张拓的博客!