57 lines
1.9 KiB
Python
57 lines
1.9 KiB
Python
from scapy.all import sniff, UDP, IP, get_if_list
|
||
import struct
|
||
|
||
# === 🧾 設定區 ===
|
||
TARGET_IP = "169.254.11.110" # 目標設備 IP
|
||
TARGET_PORT = 2312 # UDP 埠口
|
||
INTERFACE_NAME = r"\Device\NPF_{EA61A31B-056F-40E5-ADC8-5CEC3FEFDAE8}" # ✅ 換成你那張有 IP 的網卡
|
||
|
||
# === 📦 資料解析函數 ===
|
||
def analyze_payload(payload: bytes):
|
||
results = []
|
||
for i in range(0, len(payload), 8):
|
||
block = payload[i:i+8]
|
||
if len(block) < 8:
|
||
continue
|
||
try:
|
||
tag, type_code, value = struct.unpack('<H B x I', block)
|
||
results.append((f"0x{tag:04X}", type_code, value))
|
||
except struct.error:
|
||
continue
|
||
return results
|
||
|
||
# === 🖥️ 封包處理函數 ===
|
||
def handle_packet(pkt):
|
||
if UDP in pkt and IP in pkt:
|
||
ip_layer = pkt[IP]
|
||
udp_layer = pkt[UDP]
|
||
|
||
if ip_layer.src == TARGET_IP or ip_layer.dst == TARGET_IP:
|
||
print(f"\n📦 封包來自 {ip_layer.src} → {ip_layer.dst}")
|
||
payload = bytes(udp_layer.payload)
|
||
|
||
if len(payload) == 0:
|
||
print("⚠️ 無 payload,跳過")
|
||
return
|
||
|
||
result = analyze_payload(payload)
|
||
print(f"📊 分析結果,共 {len(result)} 筆:")
|
||
for tag, typ, val in result:
|
||
print(f" ➤ Tag: {tag} | Type: {typ} | Value: {val}")
|
||
|
||
# === ✅ 檢查介面是否存在 ===
|
||
if INTERFACE_NAME not in get_if_list():
|
||
print("❌ 找不到指定的網卡:", INTERFACE_NAME)
|
||
print("✅ 可選網卡如下:")
|
||
for iface in get_if_list():
|
||
print(" -", iface)
|
||
exit(1)
|
||
|
||
# === 🚀 開始監控 ===
|
||
print(f"📡 正在監控介面:{INTERFACE_NAME},目標 IP: {TARGET_IP}, Port: {TARGET_PORT}")
|
||
sniff(
|
||
iface=INTERFACE_NAME,
|
||
filter=f"udp and host {TARGET_IP} and port {TARGET_PORT}",
|
||
prn=handle_packet
|
||
)
|