def encode_packet(packet):
 packet_buff = struct.pack('!HH', packet['opcode'], packet['session_id'])
 if (packet['opcode'] in (OPCODE_RRQ, OPCODE_WRQ)):
  packet_buff += (packet['file_name'] + '\x00')
  for (k, v) in packet['options'].iteritems():
   packet_buff += ('%s\x00%s\x00' % (k, v))
 elif (packet['opcode'] == OPCODE_DATA):
  packet_buff += struct.pack('!H', packet['block_number'])
  packet_buff += packet['data']
 elif (packet['opcode'] == OPCODE_ACK):
  packet_buff += struct.pack('!H', packet['block_number'])
 elif (packet['opcode'] == OPCODE_ERROR):
  packet_buff += struct.pack('!H', packet['error_code'])
  packet_buff += (packet['error_msg'] + '\x00')
 elif (packet['opcode'] == OPCODE_OACK):
  for (k, v) in packet['options'].iteritems():
   packet_buff += ('%s\x00%s\x00' % (k, v))
 return packet_buff

def encode_packet ( packet ) : packet_buff = struct . pack ( '!HH' , packet [ 'opcode' ] , packet [ 'session_id' ] ) if ( packet [ 'opcode' ] in ( OPCODE_RRQ , OPCODE_WRQ ) ) : packet_buff += ( packet [ 'file_name' ] + '\x00' ) for ( k , v ) in packet [ 'options' ] . iteritems ( ) : packet_buff += ( '%s\x00%s\x00' % ( k , v ) ) elif ( packet [ 'opcode' ] == OPCODE_DATA ) : packet_buff += struct . pack ( '!H' , packet [ 'block_number' ] ) packet_buff += packet [ 'data' ] elif ( packet [ 'opcode' ] == OPCODE_ACK ) : packet_buff += struct . pack ( '!H' , packet [ 'block_number' ] ) elif ( packet [ 'opcode' ] == OPCODE_ERROR ) : packet_buff += struct . pack ( '!H' , packet [ 'error_code' ] ) packet_buff += ( packet [ 'error_msg' ] + '\x00' ) elif ( packet [ 'opcode' ] == OPCODE_OACK ) : for ( k , v ) in packet [ 'options' ] . iteritems ( ) : packet_buff += ( '%s\x00%s\x00' % ( k , v ) ) return packet_buff
encodes a packet dictionary into a binary string .