Search code examples
pythonpython-3.xsocketstcptcpclient

Send a single byte over TCP socket python


I am trying to write a function in python 3.x that returns a single byte of data to send over a TCP connection.

The data I am trying to send is an unsigned integer from 0-100.

I am checking the bytes used by the data with sys.getsizeof(data), but I have not come across an instance where sys.getsizeof(data) == 1 .

lets say data = 10

I have tried several different ways to store a byte:

 1) struct.pack('>b', 10)

 2) bytes(10), bytes([10])

 3) 0x10

 4) bytearray(10)

 5) b'10'

all of these have returned over double digits in byte size.

I am looking for a way in python to send a single byte over a TCP socket.


Solution

  • Python is not like C or C++. Python inherently has high overhead. You can not store data in memory, but instead, get a fully-fledged object that is stored in memory.

    When you try things like

     1) struct.pack('>b', 10)
     2) bytes(10), bytes([10])
     3) 0x10
     4) bytearray(10)
     5) b'10'
    

    These are not storing bytes directly to memory, they are creating python objects to store byte data in. Thats why sys.getsizeof(data) != 1.

    That being said there is a way around this to answer the underlying question. socket.send() requires a buffer or string and python has byte-strings. so socket.send('\x0a') would send exactly one byte. You could also return a byte string from a function.

    def return_byte_string():
        return b'\x0a'
    

    Then this could be passed into socket.send(return_byte_string()) to send a single byte over a TCP connection.