Python无法捕获超出ICMP TTL的数据包

时间:2018-07-23 15:08:10

标签: python-3.x sockets icmp

因此,我试图用python创建跟踪路由实用程序,但捕获ICMP TTL超出的数据包时遇到问题。但是我的程序捕获了回复和其他icmp类型(即3型主机无法访问)。到目前为止,这是我所做的。

    sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
    ttl = 1
    max_ttl = 128

while(ttl <= max_ttl or last_addr == dst):
        sock.settimeout(4.0)
        sock.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl)
        recv_time, reply, send_time = send_packet(sock, dst, ttl)
        sock.settimeout(0)
        ttl += 1

    def send_packet(sock, dst, ttl):
        ver = 4
        ihl = 5
        ver_ihl = (ver << 4) + ihl
        tos = 0
        len = 0
        id = 5000
        offset = 0
        ip_ttl = ttl
        proto = 1
        ip_checksum = 0
        src = socket.inet_aton('192.168.8.100')
        ip_dst = socket.inet_aton(dst)
        typ = 8
        code = 0
        check = 7249
        ident = 5656
        seq = 1
        payload = 0

        icmpPack = struct.pack('!BBHHHb', typ, code, check-ttl, ident, seq, payload)
        ipPack = struct.pack('BBHHHBBH2s2s', ver_ihl, tos, len, id, offset, ip_ttl, proto, ip_checksum, src, ip_dst)

        sendPack = icmpPack+ipPack
        sock.sendto(sendPack, (dst, 1))
        send_time = time.time()

        recv_time, reply = recv_packet(sock)

        return  recv_time, reply, send_time

    def recv_packet(sock):
        try:
            reply, addr = sock.recvfrom(65536)
        except socket.timeout:
            reply = "timed out"
        recv_time = time.time()

        return recv_time, reply

这不是完整的代码,请询问是否需要其余代码。并且请不要建议我使用库来轻松完成此操作。我需要手动完成此操作。

谢谢!

0 个答案:

没有答案