Python icmp socket server (not tcp\udp)

2020-05-24 17:11发布

I'm trying to write a socket server in Python that can receive ICMP packets.

Here's my code:

s = socket.socket(socket.AF_INET,socket.SOCK_RAW, socket.IPPROTO_ICMP)
host = socket.gethostbyname(socket.gethostname())
s.bind((host,0))
s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
s.ioctl(socket.SIO_RCVALL, socket.RCVALL_ON)

However, I dont know how to receive the packets - I tried using s.listen but it failed. What am I missing or am I completly in the wrong direction?

Thanks!

2条回答
男人必须洒脱
2楼-- · 2020-05-24 17:48

Building on the accepted answer, this code unpacks the received ICMP header and displays its data (ICMP type, code, etc)

    s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP)
    s.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
    while 1:
        recPacket, addr = s.recvfrom(1024)
        icmp_header = recPacket[20:28]
        type, code, checksum, p_id, sequence = struct.unpack('bbHHh', icmp_header)
        print "type: [" + str(type) + "] code: [" + str(code) + "] checksum: [" + str(checksum) + "] p_id: [" + str(p_id) + "] sequence: [" + str(sequence) + "]"
查看更多
▲ chillily
3楼-- · 2020-05-24 17:49

I've done this before in twisted and I set the socket up like this:

import socket

def listen():
  s = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_ICMP)
  s.setsockopt(socket.SOL_IP, socket.IP_HDRINCL, 1)
  while 1:
    data, addr = s.recvfrom(1508)
    print "Packet from %r: %r" % (addr,data)
查看更多
登录 后发表回答