python用raw socket方式接收icmp包

廉价感情. 提交于 2021-01-23 19:57:40
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':
        # windowsraw 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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!