Skip to content Skip to sidebar Skip to footer

C++ Server Cannot Read My Message From Python Client Via Socket

I have wrote a python client script to send message to the server via tcp. import socket TCP_IP = '127.0.0.1' TCP_PORT = 12003 BUFFER_SIZE = 1024 MESSAGE = b'Hello, World!' s = s

Solution 1:

Like Galik already said, Python doesn't send the length of the string before the string, like your programm expects it. And C/C++ doesn't do this either.

If you want your Python program to work with your C programm, there are several things you have to consider:

  1. Use the struct module to pack your string with the required length before it
  2. Use the network byte order when packing your string
  3. You should be aware that declarations like size_t are architecture dependant and vary between 64 and 32 bit architectures. You can use fixed size integers like uint32_t if you want them to be compatible between architectures.

Example Code:

from structimport pack
message = "Hello World"
data = pack('!i%ds' % len(message), len(message), message))

If you can't change the C-Code to use the network byte order, your specific code should look like this:

from structimport pack
message = "Hello World"
data = pack('<Q%ds' % len(message), len(message), message))

< = Use little endian byte order

Q = Use an unsigned 64 bit integer (sizet_t on 64Bit architectures)

Solution 2:

As Galik pointed out your python script does not send any length of the message. While your c++ server reads 4 bytes ( 8 if you are on 64 bit linux ) and expect them to be length of the message. So first 4 bytes are "Hell" which binary form will be quite a big number of bytes your server tries to read.

To fix this - send first 4 bytes as message length in your python script. Also you'll need to use network byte order ( if you plan to stuck with binary ) to make sure bytes read properly. Use ntohl() function to convert from network to host byte order number.

Post a Comment for "C++ Server Cannot Read My Message From Python Client Via Socket"