3

I'm sending messages over TCP/IP, I need to prefix message length in a char array and then send it. How do I do it?

Also can you please provide an example of how to extract it at the another end. And if possible, please explain.

I'm using C++ and Winsock.

EDIT:

string writeBuffer = "Hello";

unsigned __int32 length = htonl(writeBuffer.length());

It's not returning the correct length rather a very large number.

For the receiving part, if I use ntohl(), then I also get a large number instead of the correct length? Why is that so? I'm receiving like this

bool Server::Receive(unsigned int socketIndex)
{
    // Read data from the socket
    if (receivingLength)
    {
        bytesReceived = recv(socketArray[socketIndex - WSA_WAIT_EVENT_0],
            ((char*)&messageLength) + bytesReceived, MESSAGE_LENGTH_SIZE - bytesReceived, 0);

        if (bytesReceived == SOCKET_ERROR)
        {
            return false;
        }

        if (bytesReceived == MESSAGE_LENGTH_SIZE)
        {
            // If uncomment the following line,
            // I won't get the correct length, but a large number
            //messageLength = ntohl(messageLength);
            receivingLength = false;
            bytesReceived = 0;
            bytesLeft = messageLength;
        }
    }
    else
    {
        if (bytesLeft > BUFFER_SIZE)
        {
            return false;
        }

        bytesReceived = recv(socketArray[socketIndex - WSA_WAIT_EVENT_0],
            &receiveBuffer[bytesReceived], bytesLeft, 0);

        if (bytesReceived == SOCKET_ERROR)
        {
            return false;
        }

        if (bytesReceived == messageLength)
        {
            // we have received full message
            messageReceived = true;

            receiveBuffer[bytesReceived] = '\0';

            // wait for next message
            receivingLength = true;
        }

        bytesLeft -= bytesReceived;
    }

    return true;
}
5
  • htonl transforms the integer to network byte order. Your machine uses the byte order opposite to that of the network, so the number looks inadequate after conversion. Don't try to interpret htonl() result, just send it.
    – sharptooth
    Sep 4, 2009 at 11:32
  • The same applies to ntohl - you only apply it to a number in network byte order and only interpret the return value.
    – sharptooth
    Sep 4, 2009 at 11:38
  • Can you tell me how do I convert it back to my machine's byte order in .NET? (which is the client application)
    – akif
    Sep 4, 2009 at 11:44
  • I use BitConverter class to prefix length in .NET does it take care of the endianness issues? Or do I have to do it manually, if so then how do I?
    – akif
    Sep 4, 2009 at 11:49
  • 1
    I guess you could use IPAddress.NetworkToHostOrder()
    – sharptooth
    Sep 4, 2009 at 11:49

3 Answers 3

7

When sending a length field on a TCP stream, you need to decide two things:

  1. what length should the length have (1 byte, 2 bytes, 4 bytes, variable length)
  2. what endianness should I use

I recommend to use 4 bytes length, and network byte order (i.e. big-endian). For network byte order, the macros htonl and ntohl will convert between host (native) byte order (little-endian, in your case), and network byte order.

To send data, the fragment should look like this:

size_t length = strlen(data);
uint32_t nlength = htonl(length);
send(sock, &nlength, 4, 0);
send(sock, data, length, 0);

On the receiving side, you extract first the length, then the data:

uint32_t length, nlength;
recv(sock, &nlength, 4, 0);
length = ntohl(nlength);
data = malloc(length+1);
recv(sock, data, length, 0);
data[length] = 0;

What this code is missing is error handling: each of the send and receive calls may fail; the recvs may receive less data than expected. But this should give you an idea.

Edit: To deal with the case that the recv returns too few data, run it in a loop, keeping a count of what you have read so far, e.g.

int length_bytes = 0;
while(length_bytes < 4){
   int read = recv(sock, ((char*)&nLength)+length_bytes, 4-length_bytes, 0);
   if (read == -1) some_error_occurred_check_errno();
   length_bytes += read;
}
13
  • 1
    In the code sample you give, there is a buffer which may contain future data (i.e. subsequent messages). This complicates matters, but may help performance as it avoids small reads (which shouldn't really matter that much). As for error handling: it may happen that the first recv only gives you 2 bytes, not four. Then, nlength will not be fully initialized, and you pass a bogus size to malloc. That may indeed crash. More likely, you will allocate too much data, and then also try to read much more data than you will get, making you end up with nonsense in the string. Aug 27, 2009 at 7:51
  • 1
    You should not be using long. The definition of htonl() etc use uint32_t. If you use long on some systems this may potentially fail. Aug 27, 2009 at 16:49
  • 1
    @Ahmed: the bitwise operations do what ntohl does in my code, for a flexible-length representation of the packet size (although the code fixes prefix_size it to 2 bytes). The packet length is in network byte order, so it is (for 2 byte length) (byte0<<8)|byte1 == byte0*256+byte1. For 4-byte length, the packet size can be computed as (byte0<<24)|(byte1<<16)|(byte2<<8)|byte3 ... and so on. Aug 27, 2009 at 20:35
  • 1
    I recommend to use blocking sockets. If you absolutely have to use non-blocking sockets, you have to use select() in the loop also, to make it block. Sep 2, 2009 at 7:14
  • 1
    Sure. The loop only replaces the original recv call. Everything else remains (except you need another loop for the second recv). Sep 4, 2009 at 11:13
1

Pseudocode (error handling omitted, be careful):

sender:

u_long converted = htonl( messageLength ); // convert from local byte order to network byte order
send( socket, (char*)&converted, sizeof( converted ), 0 );

receiver:

u_long messageLength;
recv( socket, (char*)&messageLength, sizeof( messageLength ), 0 );
messageLength = ntohl( messageLength ); convert from network byte order to local byte order
1
0

I'm not sure if this is what you are asking, but I would send it as a string of a fixed length (let's say 4 characters, actual length up to you). In other words, if the data length is 164, send the string "0164". This gets over any problems of byte order at the other end, and is easy to read and debug.

To produce such strings, you can use a stringstream:

#include <sstream>
#include <iomanip>

std::string MakeLenStr( int n ) {
  std::ostringstream os;
  os << std::setw(4) << std::setfill('0') << n;
  return os.str();
}

To send:

std::string s = MakeLenStr( len );
send( sock, s.c_str(), 4 );

To read it at the other end, something like:

char a[5] = {0};
recv( sock, a, 4 );
int n = atoi( a );

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.