Reading an Int32 in network byte order from NetworkStream?

  • Thread starter Thread starter Scott
  • Start date Start date
S

Scott

I'm writing a C# server application that is reading from a socket sent
from a C++ client program. The C++ client program is sending the
following data:

struct
{
int stringLen;
actual ASCII string;
};

stringLen is intialized with the following C++ code:

htonl(std::string::size());

My question is, how do I read in the string length in C#? I can't
seem to locate similiar functionality in C# for the C++ call
ntohl(long);

Thanks for any help!
 
Does BitConverter not help?

What about Marshal?

Or maybe you can define the structure in C#, use StructLayoutAttribute etc.
to order the fields and then deserialize it from the byte array you get from
the .NET Socket object. Note: I've never tried this; it's just an idea...
I'm not particular hopeful that it will work.

- Lee
 
Scott said:
htonl(std::string::size());
My question is, how do I read in the string length in C#? I can't
seem to locate similiar functionality in C# for the C++ call
ntohl(long);

To convert the four bytes you've read from the stream to an integer, use
BitConverter.ToInt32. However, this method expects the bytes in little
endian order, and network byte order is big endian. So before you pass the
array to the BitConverter class you'll first have to reverse them if
necessary. Here's the code:

byte[] array = ...; // 4 bytes from stream
if (BitConverter.IsLittleEndian)
Array.Reverse(array);
int length = BitConverter.ToInt32(array, 0);

Regards,
Pieter Philippaerts
Managed SSL/TLS: http://www.mentalis.org/go.php?sl
 
Use the IPAddress Class static methods:

IPAddress.NetworkToHostOrder() or IPAddress.HostToNetworkOrder() depending
upon the direction you're going...

Dan
 
Back
Top