使用python发送自定义的MDNS请求帧

本文最后更新于 2025年5月21日 下午

要求:为了通过Python编程发送mdns帧请求测试模块是否正常工作,特编写此程序,可以用于模拟多种压力测试场景。

程序实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from scapy.all import *
from scapy.layers.dns import DNS, DNSQR
from scapy.layers.inet import IP, UDP
import socket
import time
import random

# 发送间隔(s)
send_iter = 0.001

# mDNS 组播地址和端口
MDNS_MULTICAST_IP = "224.0.0.251"
MDNS_PORT = 5353

# 要查询的服务名,可以改为 _googlecast._tcp.local. 等
query_name = "_googlecast._tcp.local"
# query_name = "MFP11810324.local"

# 构造 DNS 查询层
dns_disturb = DNS(
id=0, # mDNS 查询通常 id 为 0
qr=0, # 查询而非响应
opcode=0,
rd=0,
qdcount=1,
qd=DNSQR(qname=query_name, qtype="AAAA", qclass="IN")
# qd=DNSQR(qname=query_name, qtype="A", qclass="IN")
# qd=DNSQR(qname=query_name, qtype="ANY", qclass="IN")
)

# 构造 DNS 查询层
dns = DNS(
id=0, # mDNS 查询通常 id 为 0
qr=0, # 查询而非响应
opcode=0,
rd=0,
qdcount=1,
qd=DNSQR(qname=query_name, qtype="PTR", qclass="IN")
)

# 构造 UDP/IP 层(目标是 mDNS 组播地址和端口)
udp = UDP(sport=MDNS_PORT, dport=MDNS_PORT)
ip = IP(dst=MDNS_MULTICAST_IP)

# 发送帧(带以太网广播,适用于某些环境)
packet_disturb = ip / udp / dns_disturb
packet = ip / udp / dns

print(f"[*] Sending mDNS query for {query_name}")

cnt = 50
send_iter = 0.000001
start_time = time.time()
send(packet_disturb, iface="eth0", count=300 * cnt, inter=send_iter, verbose=0)
send(packet, iface="eth0", count=1, inter=send_iter)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"程序运行时间:{elapsed_time:.3f} 秒")

使用方法

(1)安装scapy

1
pip3 install scapy -i https://pypi.tuna.tsinghua.edu.cn/simple

(2)运行程序

1
python3 frame_test.py

使用python发送自定义的MDNS请求帧
https://www.bitzerone.com/2025/05/14/scapy-mdns/
作者
酸菜肉丝
发布于
2025年5月14日
更新于
2025年5月21日
许可协议