import socket import sys while True: r = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('ICMP')) r.settimeout(5) if sys.platform == 'win32': # windows对raw socket有限制,需要bind一个地址 # https://docs.microsoft.com/en-us/windows/win32/winsock/tcp-ip-raw-sockets-2 r.bind(("127.0.0.1", 0)) r.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON) try: packet, address = r.recvfrom(1024) ipHeaderPacket = packet[0:20] sourceIp = "%d.%d.%d.%d" % (ipHeaderPacket[12], ipHeaderPacket[13], ipHeaderPacket[14], ipHeaderPacket[15]) icmpHeaderPacket = packet[20:28] icmpType = icmpHeaderPacket[0] icmpCode = icmpHeaderPacket[1] print(f"{sourceIp}, {icmpType}, {icmpCode}") except Exception as e: print(e)
来源:oschina
链接:https://my.oschina.net/airxiechao/blog/4921601