[...]
The only difference I can really see is that your solution calls Write
twice
and some protocols preserve boundaries.
I'm taking for granted that the variable named "_stream" is in fact a
stream, from a stream-oriented protocol (e.g. TCP), in which case the
write boundaries aren't relevant. I'm especially confident of this
assumption, as you can only create a BinaryWriter instance from a stream.
I think a MemoryStream would
overcome that quite easily, or a "gather" write. Of course, I would
expect
a method called Write(Int32) to already change the byte order to some
portable endianness, whether it's the network order I have no idea.
BinaryWriter.Write(Int32) is documented to use little-endian. Either
little- or big-endian is "portable", of course...so long as everyone has
agreed on the format ahead of time (e.g. the application-level protocol
defines the correct format). But it appears that the OP is dealing with
an app-level protocol that requires big-endian, not little-endian.
Since BinaryWriter.Write(Int32) always sends the given int as
little-endian, it's reliable to simply swap the bytes of the original int
before sending in order to "fool" it into sending the original int as
big-endian.
And I definitely would not use IPAddress.HostToNetworkOrder on something
that isn't an IP address. IPAddress.HostToNetworkOrder should be
implemented by calling Int32.HostToNetworkOrder (or
Socket.Int32HostToNetworkOrder), not the other way around.
I'm not entirely sure I understand your disagreement here is. But, if
you're concerned about the use of something in the IPAddress class rather
than something less specific, sure. The API is perhaps a little awkward.
But, there's a well-established precedent for using the socket API to swap
bytes for networking purposes, even if those bytes aren't specifically for
network addresses. That is, the functions htons() and htonl() (the BSD
equivalents to the HostToNetworkOrder() methods), while existing primarily
so that ports and IP addresses can be byte-swapped, are very often used
for other byte-swapping purposes as well.
I wish .NET had better, more general-purpose endian support. But it
doesn't, and I find it very practical to simply use the built-in support
that does exist, rather than rewriting the exact implementation just so
that you can get a name you like. (Besides, if we're going to get picky
about naming, why are there even two methods -- HostToNetworkOrder() and
NetworkToHostOrder() -- that both do exactly the same thing? Why not just
have an IPAddress.SwapBytes() method?)
Pete