python之使用scapy扫描本机局域网主机,输出IP/MAC表

安装scapy库

python 复制代码
pip install scapy -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple

扫描本机局域网的所有主机,输出IP/MAC对于表

python 复制代码
# -*- coding: UTF-8 -*-
import netifaces
from scapy.all import srp
from scapy.layers.l2 import ARP, Ether
import ipaddress


def get_local_network():
    """获取本机IP段/掩码"""
    ip_mask = []
    for iface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(iface)
        if netifaces.AF_INET in addrs:
            for addr_info in addrs[netifaces.AF_INET]:
                if 'addr' in addr_info and 'netmask' in addr_info:
                    ip = addr_info['addr']
                    mask = addr_info['netmask']
                    if ip != '127.0.0.1':
                        network = ipaddress.IPv4Network(f"{ip}/{mask}", strict=False)
                        netmask = sum(bin(int(x)).count('1') for x in mask.split('.'))
                        ip_mask.append(f"{network.network_address}/{netmask}")

    return ip_mask


def scan_network(ip_range):
    """
    扫描指定 IP 范围内的主机,获取 IP 和 MAC 地址的对应关系
    :param ip_range: IP 范围,例如 "192.168.0.0/24"
    :return: IP/MAC 对应表
    """
    # ARP 请求包
    arp_request = ARP(pdst=ip_range)
    # 广播帧
    ether_frame = Ether(dst="ff:ff:ff:ff:ff:ff")
    # 数据包
    packet = ether_frame / arp_request

    # 发送并接收响应
    result = srp(packet, timeout=3, verbose=0, filter="arp")[0]

    # 解析结果
    ip_mac_table = []
    for sent, received in result:
        ip = received.psrc
        mac = received.hwsrc
        ip_mac_table.append((ip, mac))

    return ip_mac_table


def print_ip_mac_table(ip_mac_table):
    """
    打印 IP/MAC 对应表
    :param ip_mac_table: IP/MAC 对应表
    """
    print("IP/MAC 对应表:")
    print("-" * 35)
    print(f"{'IP':<15}{'MAC':<17}")
    print("-" * 35)
    for ip, mac in ip_mac_table:
        print(f"{ip:<15}{mac:<17}")
    print("-" * 35)


if __name__ == "__main__":
    ip_mac_table_result = []

    for ip_range in get_local_network():
        print(f"开始扫描 {ip_range} ...")
        ip_mac_table_result += scan_network(ip_range)

    print_ip_mac_table(ip_mac_table_result)

输出

python 复制代码
开始扫描 192.168.0.0/24 ...
IP Address       MAC Address         
--------------------------------------
192.168.0.113    4c:5f:70:6d:db:ca
相关推荐
wujj_whut17 分钟前
【Conda实战】从0到1:虚拟环境创建、多Python版本管理与环境切换全指南
开发语言·python·conda
geoqiye21 分钟前
2026官方认证:贵阳宠物行业短视频运营TOP5评测
大数据·python·宠物
龙腾AI白云33 分钟前
AI智能体搭建(3)深度搜索智能体如何搭建与设计 Agent#智能体搭建#多智能体#VLA#大模型
python·django·virtualenv·scikit-learn·tornado
海棠AI实验室36 分钟前
第十一章 错误处理体系:异常分层与可恢复策略
python·异常处理
love530love37 分钟前
EPGF 新手教程 22教学模板不是压缩包:EPGF 如何设计“可复制、可检查、可回收”的课程模板?
ide·人工智能·windows·python·架构·pycharm·epgf
ai_top_trends1 小时前
不同 AI 生成 2026 年工作计划 PPT 的使用门槛对比
人工智能·python·powerpoint
adayabetter2 小时前
Python自动化办公提效相关脚本
python·自动化·自动化脚本
二狗哈2 小时前
czsc入门8:Signal信号
python·量化·czsc
IT北辰2 小时前
【Python实战升级版】企业用电深度分析完整版|十大可视化图表+智慧能源看板,电费优化/数据汇报
python
小白学大数据3 小时前
爬虫技术选股:Python 自动化筛选潜力股
开发语言·爬虫·python·自动化