用Python来回答这个问题取决于您的平台。我手头没有Windows,所以下面的解决方案适用于我编写的Linux系统。对正则表达式进行一点小小的更改将使其在OSX中工作
首先,你必须锁定目标。这将把目标——只要它在你的网络掩码中,就像在这种情况下那样——放在你系统的ARP缓存中。注意:13:40 jsmith@undertow% ping 97.107.138.15
PING 97.107.138.15 (97.107.138.15) 56(84) bytes of data.
64 bytes from 97.107.138.15: icmp_seq=1 ttl=64 time=1.25 ms
^C
13:40 jsmith@undertow% arp -n 97.107.138.15
Address HWtype HWaddress Flags Mask Iface
97.107.138.15 ether fe:fd:61:6b:8a:0f C eth0
知道了这一点,你就做了一个小的子进程魔术——否则你自己就在写ARP缓存检查代码,你不想这么做:>>> from subprocess import Popen, PIPE
>>> import re
>>> IP = "1.2.3.4"
>>> # do_ping(IP)
>>> # The time between ping and arp check must be small, as ARP may not cache long
>>> pid = Popen(["arp", "-n", IP], stdout=PIPE)
>>> s = pid.communicate()[0]
>>> mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
>>> mac
"fe:fd:61:6b:8a:0f"