linux下除了常见的工具获取mac地址以外,还可以通过查询
cat /sys/class/net/eth0/address
来获得mac地址
但是通过ifconfig xxx hw ether xx:xx:xx:xx以后
所有获得的mac地址都是更改过的,如何获得原有网卡的真实ip呢
网上找了下方法
1:redhat下 在 /etc/sysconfig/hwconf里看到有原来的mac地址
2:写代码
c语言获取mac方法
- #include <stdio.h>
-
#include <string.h>
-
#include <sys/types.h>
-
#include <sys/socket.h>
-
#include <sys/ioctl.h>
-
#include <netinet/in.h>
-
#include <net/if.h>
-
-
int main()
-
{
-
int fd;
-
struct ifreq ifr;
-
fd = socket(AF_INET, SOCK_DGRAM, 0);
-
ifr.ifr_addr.sa_family = AF_INET;
-
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
-
ioctl(fd, SIOCGIFHWADDR, &ifr);
-
close(fd);
-
printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
-
(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 0;
-
}
python获取ip,mac方法参考(其实和c的写法基本一样)
- import socket,struct,fcntl
-
-
-
def get_hw_address(ifname):
-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-
info = fcntl.ioctl(s.fileno(),0x8927,struct.pack('256s', ifname[:15]))
-
hwaddr = []
-
print len(info)
-
for char in info[18:24]:
-
hdigit = '%02x' % struct.unpack('B',char)[0]
-
hwaddr.append(hdigit)
-
return ':'.join(hwaddr)
-
-
def getHwAddr(ifname):
-
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
-
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
-
-
-
print get_hw_address('eth1')
-
#print getHwAddr('eth1')
经过测试!!c和python的获取的mac都是改变的-v- ,所以上面两个代码找到的mac也不是真实mac
orz,失败鸟
SIOCGIFHWADDR 和 0x8927是一个意思
/usr/include/linux/sockios.h 里有定义
阅读(5514) | 评论(0) | 转发(0) |