所以,下面是我的代码。我试图建立一个通过以太网发送的特定UDP数据包。
import socket
UDP_IP = "0.0.0.0" #I have used the actual Ip address here
UDP_PORT = 8543
MESSAGE = None
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE ,"\n"
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
# struct of a first block
dict1 = {'ID': ''}
data_20 = 200
data_200 = hex(data_20)
print data_200, '\n'
# struct of 2nd block
dict2 = {'Cmd': '', 'channel': '', 'k': ''}
data_S = '0x2 0x0 0x0'
data_arr1 = data_S.split(' ')
print data_arr1, '\n'
dict2['Cmd'] = data_arr1[0]
dict2['channel'] = data_arr1[1]
dict2['k'] = data_arr1[2]
print 'k =',dict2['k'], '; Cmd = ', dict2 ['Cmd'], '; channel = ',dict2 ['channel'],"\n"
MESSAGE = data_200 + ' ' + data_S
print "message:", MESSAGE ,"\n"
sock.sendto(str(MESSAGE), (UDP_IP, UDP_PORT)) #Even if I remove the 'str' for the message I still read the same message over wireshark
这是相同的输出(我删除了IP地址)
UDP target port: 8543
message: None
0xc8
['0x2', '0x0', '0x0']
k = 0x0 ; Cmd = 0x2 ; channel = 0x0
message: 0xc8 0x2 0x0 0x0
Process finished with exit code 0
和wireshark数据相同
0020 30 78 63 38 20 30 0xc8 0
0030 78 32 20 30 78 30 20 30 78 30 x2 0x0 0x0
我没有获得与尝试发送数据包相同的值。因此,我尝试采用略有不同的方法,相同的代码在
之下
import socket
UDP_IP = "0.0.0.0" #I have used the actual Ip address here
UDP_PORT = 8543
MESSAGE = None
print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE ,"\n"
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
# struct of first block
dict1 = {'ID': ''}
data_20 = 200
data_200 = hex(data_20)
print data_200, '\n'
# struct of 2nd block
dict2 = {'Cmd': '', 'channel': '', 'k': ''}
#data_S = '0x2 0x0 0x0'
data_S = [0x02, 0x00, 0x00]
#data_arr1 = data_S.split(' ')
print data_S, '\n'
dict2['Cmd'] = data_S[0]
dict2['channel'] = data_S[1]
dict2['k'] = data_S[2]
print 'k =',dict2['k'], '; Cmd = ', dict2 ['Cmd'], '; channel = ',dict2 ['channel'],"\n"
MESSAGE = data_200 + ' ' + data_S #Evem if I remove the '' in the line I still get the same error
print "message:", MESSAGE ,"\n"
sock.sendto(str(MESSAGE), (UDP_IP, UDP_PORT))
所以在上面的方法中,我尝试使用值作为键的列表,稍后为键分配了列表。但是我得到了这样的错误
MESSAGE = data_200 + ' ' + data_S
TypeError: cannot concatenate 'str' and 'list' objects
Process finished with exit code 1
所以,现在谈到这一点,我想看看我在wireshark上发送的数据包。如何发送?我该怎么办?