如何用Python代码实现当接收到广播时在不清楚对方的IP情况下只能查询ARP表如何判断对方是否为正常主机其ARP表中没有被篡改为伪MAC地址或者是伪IP地址
要判断对方是否为正常主机,可以通过以下步骤实现:
- 获取本机的MAC地址和IP地址
import subprocess
import re
# 获取本机的MAC地址
mac_addr = subprocess.check_output("ifconfig | grep 'ether' | awk '{print $2}'", shell=True).decode().strip()
# 获取本机的IP地址
ip_addr = subprocess.check_output("ifconfig | grep 'inet ' | awk '{print $2}'", shell=True).decode().strip()
- 查询ARP表,获取对方的MAC地址和IP地址
import os
import re
# 查询ARP表
arp_output = os.popen('arp -a').read()
# 从ARP表中获取对方的MAC地址和IP地址
mac_regex = re.compile(r'([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}')
ip_regex = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
mac_addr_list = mac_regex.findall(arp_output)
ip_addr_list = ip_regex.findall(arp_output)
# 去重
mac_addr_list = list(set(mac_addr_list))
ip_addr_list = list(set(ip_addr_list))
- 判断对方的MAC地址和IP地址是否合法
# 判断对方的MAC地址是否合法
if mac_addr in mac_addr_list:
print("对方的MAC地址合法")
else:
print("对方的MAC地址不合法")
# 判断对方的IP地址是否合法
if ip_addr in ip_addr_list:
print("对方的IP地址合法")
else:
print("对方的IP地址不合法")
如果对方的MAC地址和IP地址都合法,则可以认为对方是正常主机。如果对方的MAC地址或者IP地址不合法,则可能是伪造的MAC地址或者IP地址,需要进一步验证
原文地址: http://www.cveoy.top/t/topic/fyO1 著作权归作者所有。请勿转载和采集!