有3个代码需要执行以下操作:
由于某种原因,在C部分中,当我比较CRC时,它们永远不相等,我想念的是什么?
A部分:
import socket
import struct
import sys
import binascii
def crc32(v):
r = binascii.crc32(v.encode())
return r
if len(sys.argv) != 3:
print("Useage: python " + sys.argv[0] + " <ip> <liseten port>")
sys.exit(-1)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while True:
print("Input text:")
text = sys.stdin.readline().strip()
ss = struct.pack("!50sL",text.encode(),crc32(text))
s.sendto(ss,(sys.argv[1],int(sys.argv[2])))
if text == "bye":
break
B部分:
import socket
import operator
import sys
import binascii
import struct
import random
def crc32(v):
return binascii.crc32(v.encode())
if len(sys.argv) != 3:
print("Useage: python " + sys.argv[0] + " <liseten port>")
sys.exit(-1)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", int(sys.argv[1])))
print("Waiting...")
while True:
data, addr = s.recvfrom(1024)
str,crc = struct.unpack("!50sL",data)
str = str.decode("utf-8").replace("\0","")
if random.randint(0,100) < 40:
str = str + "x"
print("str:%s\ncrc:%X" % (str,crc & 0xffffffff))
str2 = str.encode("utf-8")
tpack = struct.pack("!50sL", str2, crc)
s.sendto(tpack,("127.0.0.1",int(sys.argv[2])))
if str == "bye":
break
C部分:
import socket
import operator
import sys
import binascii
import struct
def crc32(v):
return binascii.crc32(v.encode())
if len(sys.argv) != 2:
print("Useage: python " + sys.argv[0] + " <liseten port>")
sys.exit(-1)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("0.0.0.0", int(sys.argv[1])))
print("Waiting...")
while True:
data, addr = s.recvfrom(1024)
str,crc = struct.unpack("!50sL",data)
str = str.decode("utf-8")
print("str:%s\ncrc:%X" % (str,crc & 0xffffffff))
ncrc = crc32(str)
if ncrc == crc:
print("both messages are the same")
if str == "bye":
break
答案 0 :(得分:1)
您忘记替换C部分中的空字节。打包到50个字节之前,您在A部分中计算了CRC,并在显示接收到的值时在B部分中将其删除。
str = str.decode("utf-8")
应该b:
str = str.decode("utf-8").replace('\0','')
注意:str
是一个内置函数,您不能将其用作变量名。