Search code examples
pythontcpbyte

Send byte over tcp python?


I am going to send a byte string over tcp channel by python, the bit string has 3 bytes "000010010000000000001001" that if I look at it as 3 integers it is '909'

Sender Code:

import socket
import struct
TCP_IP = '127.0.0.1' 
TCP_PORT = 5005      
BUFFER_SIZE = 1024
MESSAGE = b"000010010000000000001001"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print( "received data:", data)

Receiver Code:

import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
conn, addr = s.accept()
print('Connection address:', addr)
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    print( "received data:", data)
    conn.send(data)  
conn.close()

I run the programs and captured the data with Wireshark and the packets were totally different, in hex representation:

30 30 30 30 31 30 30 31 30 30 30 30 30 30 30 30 30 30 30 30 31 30 30 31

So instead of sending bytes, I am sending strings. hex(ord('1')) == 0x31 and hex(ord('0')) == 0x30.

How can I really send bytes?


Solution

  • The problem does not lie in the TCP part but only in the byte part. By definition b"000010010000000000001001" is a byte string (bytes type in Python 3) containing 24 bytes (not bits) - note: a byte has 8 bits...

    So you need:

    ...
    MESSAGE = b'\x09\x00\x09'
    ...
    

    or at least

    MESSAGE = b"000010010000000000001001"
    MESSAGE = bytes((int(MESSAGE[i:i+8], 2) for i in range(0, len(MESSAGE), 8)))