title: Python send/ recv binary data
body: <p>I a trying to send and receive binary data in python(v3). The way I am attempting to do it is at the client end, I manually create a string of bytes and then send it through a socket to the server. On the server side, I receive the data and manually access individual bits to resolve the message.</p>
  
  <p>This is how the client looks:</p>
  
  <pre><code>remoteIP = "164.107.112.72"
  remotePort = 34562
  remoteStruct = remoteIP.split('.', 4)
  remoteIPBytes = ((int)(remoteStruct[0])).to_bytes(1, byteorder='little') + ((int)(remoteStruct[1])).to_bytes(1, byteorder='little') + ((int)(remoteStruct[2])).to_bytes(1, byteorder='little') + ((int)(remoteStruct[3])).to_bytes(1, byteorder='little')
  
  headerStruct = remoteIPBytes + remotePort.to_bytes(2, byteorder='little')
  sequenceNum = 0
  size = #filesize
  
  data = headerStruct + sequenceNum.to_bytes(1, byteorder='little') + (1).to_bytes(1,byteorder='little') + size.to_bytes(4, byteorder='little')
  #data is then sent to server
  </code></pre>
  
  <p>this is how the server handles the data:</p>
  
  <pre><code>serversock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)   # UDP Datagram
  host = '164.107.112.70'
  serversock.bind((host, localPort))
  
  seqNum = 0
  
  #get size
  size = 0
  var = serversock.recvfrom(12)
  seqNum = int.from_bytes((str(var))[6], byteorder='little')
  </code></pre>
  
  <p>In that last line of code, I get an error saying that (str(var)) is being treated as a unicode string rather than a binary one. However, if I don't cast as a string, I get an access out of bounds error.</p>
  
  <p>Can someone explain to me what the correct way to send and receive binary data in python is? I have tried using struct.pack and unpack before/after sending data, but I always get errors during the unpacking, even though the format strings are identical</p>