packet.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. class packet:
  2. MAX_DATA_LENGTH = 500
  3. SEQ_NUM_MODULO = 32
  4. # type is 0=ACK, 1=data, 2=EOT
  5. # seq_num is the sequence number (mod 32)
  6. # data is the string which is the data (empty if no data)
  7. def __init__(self, type, seq_num, data):
  8. if len(data) > self.MAX_DATA_LENGTH:
  9. raise Exception("Data too large (max 500 char): ", len(data))
  10. self.type = type
  11. self.seq_num = seq_num % self.SEQ_NUM_MODULO
  12. self.data = data
  13. def get_udp_data(self):
  14. array = bytearray()
  15. array.extend(self.type.to_bytes(length=4, byteorder="big"))
  16. array.extend(self.seq_num.to_bytes(length=4, byteorder="big"))
  17. array.extend(len(self.data).to_bytes(length=4, byteorder="big"))
  18. array.extend(self.data.encode())
  19. return array
  20. @staticmethod
  21. def create_ack(seq_num):
  22. return packet(0, seq_num, "")
  23. @staticmethod
  24. def create_packet(seq_num, data):
  25. return packet(1, seq_num, data)
  26. @staticmethod
  27. def create_eot(seq_num):
  28. return packet(2, seq_num, "")
  29. @staticmethod
  30. def parse_udp_data(UDPdata):
  31. type = int.from_bytes(UDPdata[0:4], byteorder="big")
  32. seq_num = int.from_bytes(UDPdata[4:8], byteorder="big")
  33. length = int.from_bytes(UDPdata[8:12], byteorder="big")
  34. if type == 0:
  35. return packet.create_ack(seq_num)
  36. elif type == 2:
  37. return packet.create_eot(seq_num)
  38. else:
  39. UDPdata = UDPdata[12:12 + length].decode()
  40. return packet(type, seq_num, UDPdata)