title: How can I unmask data from client using python
body: <p>I'm writing my own server using python that gets data from the client and I've read online that the client masks its data when sending to the server. I've got the whole handshaking thing down but I just haven't found a code that will unmask the packet. I've found a code that claims to do this but its just not working for me. Is there a pre-made function or package that does this? Any help would be greatly appreciated.</p>
  
  <p>Down below is my code:</p>
  
  <pre><code># -----------------LISTEN FOR INCOMING DATA FUNCTION----------------- #
  
  def listening_for_msgs(conn):
  while True:
      try:
          rcv_msg = conn.recv(1024) #conn is the connection to the client
          rcv_msg_str = str(rcv_msg[:].decode("utf-8"))
          rcv_msg_list = rcv_msg_str.split('\r\n')
          if rcv_msg_list[0] == 'GET /echo HTTP/1.1':
              HandshakeThread = startHandshakeThread(rcv_msg_str, conn)
              HandshakeThread.start()
          else:
              print(unmask_data(rcv_msg))
      except UnicodeDecodeError:
          unmask_data(rcv_msg)
  
  # -----------------UNMASKING CLIENTS PACKET FUNCTION----------------- #  
  
  def unmask_data(rcv_msg):
      # as a simple server, we expect to receive:
      #    - all data at one go and one frame
      #    - one frame at a time
      #    - text protocol
      #    - no ping pong messages
  data = bytearray(rcv_msg)
  if len(data) &lt; 6:
      raise Exception("Error reading data")
  # FIN bit must be set to indicate end of frame
  assert(0x1 == (0xFF &amp; data[0]) &gt;&gt; 7)
  # data must be a text frame
  # 0x8 (close connection) is handled with assertion failure
  assert(0x1 == (0xF &amp; data[0]))
  
  # assert that data is masked
  assert(0x1 == (0xFF &amp; data[1]) &gt;&gt; 7)
  datalen = (0x7F &amp; data[1])
  
  # print("received data len %d" %(datalen,))
  
  str_data = ''
  if datalen &gt; 0:
      mask_key = data[2:6]
      masked_data = data[6:(6 + datalen)]
      unmasked_data = [masked_data[i] ^ mask_key[i % 4] for i in     range(len(masked_data))]
      str_data = str(bytearray(unmasked_data))
  return str_data
  </code></pre>