龙空技术网

获取Linux系统的MAC地址和IP地址(C语言版)

编码小哥 78

前言:

而今兄弟们对“linux mac地址查看”大体比较讲究,各位老铁们都需要了解一些“linux mac地址查看”的相关内容。那么小编也在网上汇集了一些对于“linux mac地址查看””的相关内容,希望姐妹们能喜欢,各位老铁们快快来学习一下吧!

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <netdb.h>

#include <ifaddrs.h>

#include <sys/ioctl.h>

#include <net/if.h>

#include <linux/if_ether.h>

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地址。

标签: #linux mac地址查看 #linux 查mac地址查询 #linux命令查mac地址 #查询linux的mac地址