python - 从通过 Python 原始套接字接收的 ICMP 消息中读取 TTL

标签 python sockets datagram icmp raw-sockets

我正在构建一个类似路由跟踪的工具,用于仅使用一次探测来确定 UDP 数据包到达某个地址所需的跳数。为此,我想从发送探测后收到的 ICMP 消息中提取 TTL。我正在执行以下操作并成功接收 ICMP 消息:

data, source = in_socket.recvfrom(d_bufsize)

但我不知道如何将 data 转换为可以读取 TTL 的内容。 in_socket 声明如下:

in_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, icmp_proto)

这里,icmp_proto只是ICMP的协议(protocol)号(通过执行icmp_proto = socket.getprotobyname("icmp")获得)。

任何帮助将不胜感激!

最佳答案

But I have no idea how to turn data into something that I can read the TTL from.

pyping这样做:

    def header2dict(self, names, struct_format, data):
        """ unpack the raw received IP and ICMP header informations to a dict """
        unpacked_data = struct.unpack(struct_format, data)
        return dict(zip(names, unpacked_data))
…

            packet_data, address = current_socket.recvfrom(ICMP_MAX_RECV)

            icmp_header = self.header2dict(
                names=[
                    "type", "code", "checksum",
                    "packet_id", "seq_number"
                ],
                struct_format="!BBHHH",
                data=packet_data[20:28]
            )

            if icmp_header["packet_id"] == self.own_id: # Our packet
                ip_header = self.header2dict(
                    names=[
                        "version", "type", "length",
                        "id", "flags", "ttl", "protocol",
                        "checksum", "src_ip", "dest_ip"
                    ],
                    struct_format="!BBHHHBBHII",
                    data=packet_data[:20]
                )
                packet_size = len(packet_data) - 28
                ip = socket.inet_ntoa(struct.pack("!I", ip_header["src_ip"]))

然后可以从 ip_header["ttl"] 读取 TTL。

关于python - 从通过 Python 原始套接字接收的 ICMP 消息中读取 TTL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36778544/

相关文章:

python - 为什么 Keras fit_generator() 在实际 "training"之前加载

c# - Windows 10 中 UDP 的问题。UWP

java - UDP 发送多个分割字符串

java - 套接字未正确关闭

python - Python ctypes 字段中的回调函数

python - 使用 Mayavi 以交互方式绘制 3d 图的简单方法?

python - 使用 pandas 数据框和 gspread 更新现有的谷歌表格

c - 在 C 中,如何将接收到的 rtp 数据包存储到 .pcap 文件中 - UDP

c++ - 关于发送/接收的问题

python - 客户端只向服务器发送一次数据