Python raw socket listening for UDP packets; only half of the packets received

后端 未结 1 622
感动是毒
感动是毒 2021-02-04 17:48

I am trying to create a raw socket in Python that listens for UDP packets only:

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW,         


        
1条回答
  •  野性不改
    2021-02-04 18:25

    Solved it in kind of a silly manner; please let me know if there is another way, and I will change the accepted answer.

    The solution is simply to use two sockets bound on the same port; one raw, one not raw:

    import socket, select
    s1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s1.bind(('0.0.0.0', 1337))
    s2 = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_UDP)
    s2.bind(('0.0.0.0', 1337))
    while True:
        r, w, x = select.select([s1, s2], [], [])
        for i in r:
            print i, i.recvfrom(131072)
    

    This makes the "Destination unreachable" ICMP packets go away and makes all packets go through fine. I think the operating system wants a non-raw socket listening on the port for things to go well, and then any raw sockets listening on that same port will receive copies of the packets.

    0 讨论(0)
提交回复
热议问题