from scapy.all import sniff, IP, UDP
import socket

# 获取本机IP
def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except:
        return "127.0.0.1"

TARGET_PORT = 4705
MY_IP = get_local_ip()
TEACHER_IP = "10.139.199.78"  # 教师端合法IP

def detect_attack(packet):
    if IP in packet and UDP in packet:
        if packet[UDP].dport == TARGET_PORT and packet[IP].dst == MY_IP:
            src_ip = packet[IP].src

            # 不是教师端IP → 判定为冷麟攻击
            if src_ip != TEACHER_IP:
                print(f"[⚠️ 冷麟攻击] IP: {src_ip}")
            else:
                print(f"[✅ 教师端正常] IP: {src_ip}")

print("=== 冷麟IP监控已启动(仅检测、不拉黑)===")
print(f"✅ 信任IP: {TEACHER_IP}")
print("⚠️ 其他IP访问4705端口将提示为冷麟攻击\n")
sniff(prn=detect_attack, store=0)