Getting audio file from a UDP packet

我的梦境 提交于 2020-01-06 05:28:14

问题


Posting this here out of desperation. Any help is appreciated. Thank you.

Backstory:

I am helping my friend with a device that he got from China. The device supposedly sends a audio file to my server using UDP.


回答1:


assuming you want some Python code to do this automatically, here's how I'd validate and decode the packet:

import struct

def decode_packet(packet):
    framehead, version, command, datalen = struct.unpack_from('!HBBH', packet)

    valid = (
        framehead == 0x55aa and
        version == 0x00 and
        command == 0x1e and
        len(packet) <= datalen + 11
    )
    if not valid:
        # ignore other protocols using this address/port
        print(
            '  header invalid',
            f'{framehead:04x} {version:02x} {command:02x} {datalen:04x}'
        )
        return

    if len(packet) < datalen + 11:
        print('  warning: packet was truncated')

    offset, = struct.unpack_from('!I', packet, 6)
    if datalen == 4:
        print(f'  end of data: file size={offset}')
        return

    data = packet[10:10+datalen]
    print(f'  got data: offset={offset} len={len(data)} hex(data)={data.hex()}')

    if len(packet) == datalen + 11:
        print(f'  hex(checksum)={packet[datalen + 10:].hex()}')

it obviously prints out a lot of stuff, but this is good to seeing if the device is actually following the documented protocol. it doesn't seem to be, as the +4 on the data length doesn't seem to be being applied. you can test this with:

decode_packet(bytes.fromhex('55aa001e038400000000a9b6ad98d2923...'))

assuming you can get this to function correctly, you can put this into some code that listens for packets on the correct port:

import socket

def server(portnum):
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
        sock.bind(('', portnum))

        while True:
            packet, addr = sock.recvfrom(10240)
            print(f'received {len(packet)} bytes from {addr[0]}')
            decode_packet(packet)

again, doesn't do much. you'd want to write the data to a file rather than printing it out, but you can pull the offset out and you get a signal for when the data has finished transferring



来源:https://stackoverflow.com/questions/58725656/getting-audio-file-from-a-udp-packet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!