There are 3 codes that need to do the following actions:
For some reason, in part C when I compare the CRC's they are never equal, what am I missing?
Part 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
Part 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
Part 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
You forgot to replace the null bytes in Part C. You calculated the CRC in Part A before packing to 50 bytes, and removed them in Part B when displaying the received value.
str = str.decode("utf-8")
should b:
str = str.decode("utf-8").replace('\0','')
Note: str
is a builtin function that you lose access to by using it as a variable name.
User contributions licensed under CC BY-SA 3.0