def _send_with_length_prefix(self, message: bytes): message = int_to_four_bytes_big_endian(len(message)) + message try: self._socket.send(message) except Exception as ex: self._client.log.error("Exception during sending: " + str(ex)) self._client.close()
def _generate_announce(connection_id, params): action = int_to_four_bytes_big_endian(1) transaction_id = int_to_four_bytes_big_endian(Random().randint(0, 2**31)) info_hash = params["info_hash"] peer_id = params["peer_id"] downloaded = params["downloaded"].to_bytes(8, byteorder='big') left = params["left"].to_bytes(8, byteorder='big') uploaded = params["uploaded"].to_bytes(8, byteorder='big') if "event" in params: event = params["event"] if event == "completed": event = 1 elif event == "started": event = 2 elif event == "stopped": event = 3 else: event = 0 event = int_to_four_bytes_big_endian(event) ip_address = int_to_four_bytes_big_endian(0) key = int_to_four_bytes_big_endian(0) if "numwant" in params: num_want = params["numwant"] else: num_want = 50 num_want = int_to_four_bytes_big_endian(num_want) port = params["port"].to_bytes(2, byteorder='big') message = connection_id + action + transaction_id + \ info_hash + peer_id + \ downloaded + left + uploaded + \ event + ip_address + key + num_want + port return transaction_id, message
def send_cancel(self, piece_index: int, begin: int, length: int): message = Messages.cancel + \ int_to_four_bytes_big_endian(piece_index) + \ int_to_four_bytes_big_endian(begin) + \ int_to_four_bytes_big_endian(length) self._send_with_length_prefix(message)
def send_piece(self, piece_index: int, begin: int, piece: bytes): message = int_to_four_bytes_big_endian(piece_index) + \ int_to_four_bytes_big_endian(begin) + piece self._send_with_length_prefix(message)
def send_have(self, piece_index: int): message = Messages.have + int_to_four_bytes_big_endian(piece_index) self._send_with_length_prefix(message)
def _generate_connect_request(): protocol_id = b"\x00\x00\x04\x17'\x10\x19\x80" action = int_to_four_bytes_big_endian(0) transaction_id = int_to_four_bytes_big_endian(Random().randint(0, 2**31)) message = protocol_id + action + transaction_id return transaction_id, message