Python UDP数据包与Wireshark捕获不一致问题求助
Hey there! Let's break down why your current approaches aren't working and how to send the exact binary UDP packets you want Wireshark to capture.
Why Your First Code Failed
In your first attempt, you're using hex() which returns string representations of hex values (like '0xc8'). When you concatenate these strings and send them, you're actually sending the ASCII bytes of the characters '0', 'x', 'c', '8', etc. That's exactly why Wireshark shows those ASCII values instead of the binary bytes you intended.
Why Your Second Code Failed
Your second code tries to use a list of numeric hex values, but you're still trying to concatenate it with a string (data_200 is the string '0xc8' from hex(200)). Python can't mix strings and lists in concatenation, hence the TypeError.
The Correct Way to Send Binary UDP Packets
To send actual binary data, you need to construct a byte sequence that represents your desired hex values. The best tool for this in Python is the struct module, which lets you pack numeric values into properly formatted binary bytes. Alternatively, you can directly create a bytearray (Python 2/3 compatible) with your target values.
Example Working Code (Python 2)
import socket import struct UDP_IP = "0.0.0.0" # Replace with your actual target IP UDP_PORT = 8543 # Define your values as integers (200 = 0xc8, 2 = 0x02, etc.) id_value = 200 cmd_value = 0x02 channel_value = 0x00 k_value = 0x00 # Pack the values into a binary byte string # 'B' means unsigned char (1 byte per value) MESSAGE = struct.pack('BBBB', id_value, cmd_value, channel_value, k_value) print "UDP target IP:", UDP_IP print "UDP target port:", UDP_PORT print "Raw message bytes:", [ord(b) for b in MESSAGE] # Show hex values for verification sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
Alternative: Using bytearray (Python 2/3)
If you prefer a simpler approach without struct, you can create a bytearray directly from your integer values:
# For Python 2, convert bytearray to str for socket.sendto MESSAGE = str(bytearray([200, 0x02, 0x00, 0x00])) # For Python 3, just use bytes directly # MESSAGE = bytes([200, 0x02, 0x00, 0x00])
What This Does
struct.pack('BBBB', ...)takes your four integer values and converts each into a single binary byte (0xc8, 0x02, 0x00, 0x00 respectively).- When you send this byte string via
sendto(), Wireshark will capture the exact hex values you expect, not ASCII representations of hex strings.
Verification
After running this code, check Wireshark: you should see the payload as c8 02 00 00 (or formatted as 0xc8 0x02 0x00 0x00) instead of the ASCII characters from your first attempt.
内容的提问来源于stack exchange,提问作者Newbee

