【发布时间】:2013-02-19 10:45:08
【问题描述】:
操作系统:REDHAT LINUX Linux 管理:2.6.18.8-1 #
这样可以直接从网卡读取MAC地址吗?我有下面的代码,但它只是从上层读取而不是卡本身!!!
我试图弄清楚如何在我的 linux 机器上找到以太网 NIC 的原始 MAC 地址。我了解如何使用 ifconfig 查找当前 MAC 地址,但如果地址已更改,请使用
'ifconfig eth0 hw ether uu:vv:ww:yy:xx:zz',或者我使用vi /etc/sysconfig/network-scripts/ifcfg-eth0.this 文件将它设置为“永久”...我也可以在REBOOT 中成功地UP 它。如何找到原件?一定有办法找到它,因为它仍然被永久烧录到卡中,但我找不到读取烧录地址的工具。
是否有任何实用程序或命令?
我想为它编写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 和卡是如何工作的,但如果 MAC 仅在卡固件初始化时在电源循环中恢复,那将是完全合理的。
-
我只想用 SPOOFED MAC UP 我的机器,我可以成功地做到这一点。但在此期间,我想要我的原始 MAC 用于我的应用程序。那是我的问题。
-
我认为@AmigableClarkKant 暗示完整的电源循环可能会使 NIC 从固件初始化。不要只是重新启动;关机,等待,开机。这可能会使用其原始 MAC 地址重新启动 NIC。然后,您可以在运行时在更改它之前检索并存储原始 MAC 地址。
-
ohh.... 我不知道如何务实地做到这一点.. 没有其他方法可以在我的应用程序中随时获取它...使用 C 代码(不存储它某处)
-
这是一个“你如何获得该信息”的问题,假设它是可用的。网卡的所有驱动程序都知道如何执行此操作,但就像我在下面描述的那样,信息被读取然后存储,如果稍后被覆盖,那就是它 - 消失了。您可以向每个驱动程序添加一些代码,但这将是很多工作,并且几乎可以肯定不会进入 Linux 内核,因此您将永远为每个可用的网络驱动程序携带一个补丁 - 这将是相当多的努力维护...
标签: linux sockets linux-kernel linux-device-driver mac-address