是否可以直接从网卡读取 MAC 地址?我有下面的代码,但它只是从上面的层读取,而不是卡本身。
我试图弄清楚如何在我的 Linux 机器上找到以太网 NIC 的原始 MAC 地址。我了解如何使用 ifconfig 查找当前 MAC 地址。
但是可以更改地址,例如使用
ifconfig eth0 hw ether uu:vv:ww:yy:xx:zz
或使用“永久”设置它 /etc/sysconfig/network-scripts/ifcfg-eth0
。
如何找到原始 MAC 地址?一定有办法找到它,因为它仍然被永久烧录到卡中,但我找不到读取烧录地址的工具。
是否有任何实用程序或命令?
我想应该可以为它编写 C 代码,下面的代码给出了我 当前 的 MAC 但不是原始 MAC:
#include <stdio.h> /* Standard I/O */
#include <stdlib.h> /* Standard Library */
#include <errno.h> /* Error number and related */
#define ENUMS
#include <sys/socket.h>
#include <net/route.h>
#include <net/if.h>
#include <features.h> /* for the glibc version number */
#if __GLIBC__ >= 2 && __GLIBC_MINOR >= 1
#include <netpacket/packet.h>
#include <net/ethernet.h> /* the L2 protocols */
#else
#include <asm/types.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h> /* The L2 protocols */
#endif
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <sys/ioctl.h>
#include <netdb.h>
int main( int argc, char * argv[] ){
unsigned char mac[IFHWADDRLEN];
int i;
get_local_hwaddr( argv[1], mac );
for( i = 0; i < IFHWADDRLEN; i++ ){
printf( "%02X:", (unsigned int)(mac[i]) );
}
}
int get_local_hwaddr(const char *ifname, unsigned char *mac)
{
struct ifreq ifr;
int fd;
int rv; // return value - error value from df or ioctl call
/* determine the local MAC address */
strcpy(ifr.ifr_name, ifname);
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
if (fd < 0)
rv = fd;
else {
rv = ioctl(fd, SIOCGIFHWADDR, &ifr);
if (rv >= 0) /* worked okay */
memcpy(mac, ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
}
return rv;
}
操作系统:红帽 Linux,2.6.18.8-1
原文由 Jatin Bodarya 发布,翻译遵循 CC BY-SA 4.0 许可协议
当然在 ethtool 你可以打印地址:
”`
生产