3

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?

2
  • 1
    Hrm, are you sure that wireshark doesn't just use the hex format to display the package content at the point of interception? You certainly pass in bytes and you certainly get them out again. In the end, there's a lot of witchcraft and black magic happening to your playload on its way through the layers of the stack. You cannot control how your data looks on the wire purely from the application layer. Commented Jun 14, 2018 at 8:12
  • 1
    You are getting exactly what you are sending because b"00001001" is a byte string of length 8 bytes, composed of '0' and '1' characters. Commented Jun 14, 2018 at 8:37

1 Answer 1

8

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)))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.