当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Why is the first letter of the char array being cut off during this ssl write procedure?

问题描述:

I am using TCP sockets in c and sending data across the network to another machine encrypted using SSL. However, for some reason that I cannot seem to figure out, the first letter of the sentence being written to the socket is cut off.

The server side program is writing the data to the socket with the line:

err = SSL_write (ssl, "This is a message", strlen("This is a message"));

and the following function on the client is used to retrieve the data from the socket (vb.net):

Public Function TCPRead(ByVal SecureSocket As SslStream)

Dim bytes(SecureSocket.ReadByte) As Byte

SecureSocket.Read(Bytes, 0, Bytes.Count)

Return Encoding.ASCII.GetString(Bytes)

End Function

However, the string returned from the socket on the client side is:

his is a message

The manual for ssl_write (https://linux.die.net/man/3/ssl_write) says that:

SSL_write() writes num bytes from the buffer buf into the specified ssl connection.

So surely the above C code above writes the chars from the sentence above equal to that of the amount of letters in the char array?

I'm worried that this might be something really stupid that I can't see.

Thanks

网友答案:

My basic is weak, but I've a bad feeling you're consuming the first byte in the message here: Dim bytes(SecureSocket.ReadByte) As Byte, trying to use it as the size of the message.

C and C++ don't advertise string length in the first byte. They mark the end of the string with a null character. strlen computes the length of the string by reading and counting until it finds the null character.

If you want to prepend the length, you'll have to do something like

const char* msg = "This is a message";
uint8_t len = strlen(msg); // note: this will fail hilariously 
                           // if the string is greater than 255 characters
SSL_write (ssl, &len, sizeof(len)); // note - totally ignoring errors here
SSL_write (ssl, msg, len);

If C++ is on the table, and it's been tagged so it better be,

std::string str = "This is a message";
uint8_t len = str.length(); // note: this will fail hilariously if the string 
                            // is greater than 255 characters long
SSL_write (ssl, &len, sizeof(len)); // note - totally ignoring errors here
SSL_write (ssl, str.c_str(), len);
分享给朋友:
您可能感兴趣的文章:
随机阅读: