#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
void get_mac_address(char *mac, int size) {
struct ifreq ifr;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) {
perror("socket");
exit(1);
}
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == -1) {
perror("ioctl");
exit(1);
}
snprintf(mac, size, "%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]);
close(sock);
}
void get_ip_address(char *ip, int size) {
struct ifaddrs *ifaddr, *ifa;
int family, s;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(1);
}
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (!ifa->ifa_addr) {
continue;
}
family = ifa->ifa_addr->sa_family;
if (family == AF_INET || family == AF_INET6) {
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");
exit(1);
}
strncpy(ip, host, size);
break;
}
}
freeifaddrs(ifaddr);
}
int main() {
char mac[18];
char ip[INET6_ADDRSTRLEN];
get_mac_address(mac, sizeof(mac));
get_ip_address(ip, sizeof(ip));
printf("MAC地址: %s", mac);
printf("IP地址: %s", ip);
return 0;
}
这段代码定义了两个函数`get_mac_address`和`get_ip_address`,分别用于获取MAC地址和IP地址。