You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Scapy捕获的数据包列表转为字符串列表以通过JSON发送API请求

Scapy数据包序列化为JSON字符串列表问题

问题描述

我正在尝试将Scapy捕获的数据包序列化,通过API调用以JSON对象形式发送。当前API服务器期望packets字段接收字符串列表,但我不知道如何把Scapy数据包列表转换成符合要求的格式。

现有API调用代码

def load_points(packet_list, permanent):
    print("loading points")

    waypoint_url = ''
    if(permanent):
        waypoint_url = "/add_permanent_points_packets"
    else:
        waypoint_url = "/add_temporary_points_packets"
    
    response = requests.post(
        URL+waypoint_url,
        json={        
        "lidar_params": {
                "azimuth_degrees": 0.5,
                "elevation_degrees": 5,
                "radial_resolution": 2,
                "max_elevation": 15,
                "min_elevation": -15,
                "max_radius": 100,
                "floor_height": beacon_height,
                "latitude": beacon_latitude,
                "longitude": beacon_longitude
            },
        "packets": json.dumps(packet_list)
        },
    )
    print(response.text)

数据包捕获代码

sniff(prn=permanent_packet_callback, iface="Ethernet 5",count=revolution_count)

def permanent_packet_callback(packet):
    global packet_list, done_waiting

    # append to list
    packet_list.append(packet)

解决方案

Scapy数据包对象无法直接序列化为JSON,需要先将每个数据包转换为字符串格式,以下是两种常用方式:

  • 十六进制字符串格式(推荐用于保留原始数据)
    利用bytes()将数据包转为字节流,再通过hex()方法转为十六进制字符串:

    packet_strings = [bytes(packet).hex() for packet in packet_list]
    
  • 人类可读字符串格式(适合调试场景)
    直接调用str()获取数据包的简洁字符串表示,或用show(dump=True)获取详细输出:

    # 简洁字符串
    packet_strings = [str(packet) for packet in packet_list]
    # 详细输出字符串
    packet_strings = [packet.show(dump=True) for packet in packet_list]
    

修改后的API调用代码

将packets字段替换为转换后的字符串列表即可,无需额外用json.dumps()包裹(requests.post的json参数会自动完成序列化):

def load_points(packet_list, permanent):
    print("loading points")

    waypoint_url = ''
    if(permanent):
        waypoint_url = "/add_permanent_points_packets"
    else:
        waypoint_url = "/add_temporary_points_packets"
    
    # 转换数据包列表为十六进制字符串列表
    packet_strings = [bytes(packet).hex() for packet in packet_list]
    
    response = requests.post(
        URL+waypoint_url,
        json={        
        "lidar_params": {
                "azimuth_degrees": 0.5,
                "elevation_degrees": 5,
                "radial_resolution": 2,
                "max_elevation": 15,
                "min_elevation": -15,
                "max_radius": 100,
                "floor_height": beacon_height,
                "latitude": beacon_latitude,
                "longitude": beacon_longitude
            },
        "packets": packet_strings
        },
    )
    print(response.text)

内容的提问来源于stack exchange,提问作者youcantgetridofmestackoverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 06:10:16