Martin
Martin

Reputation: 12403

C# Network encoding

I'm working on a networking application in C#, sending a lot of plain numbers across the network. I discovered the IPAddress.HostToNetworkOrder and IPAddress.NetworkToHostOrder methods, which are very useful, but they left me with a few questions:

  1. I know I need to encode and decode integers, what about unsigned ones? I think yes, so at the moment I'm doing it by casting a pointer to the unsigned int into a pointer to an int, and then doing a network conversion for the int (since there is no method overload that takes unsigned ints)

    public static UInt64 HostToNetworkOrder(UInt64 i)
    {
        Int64 a = *((Int64*)&i);
        a = IPAddress.HostToNetworkOrder(a);
        return *((UInt64*)&a);
    }
    
    public static UInt64 NetworkToHostOrder(UInt64 a)
    {
        Int64 i = *((Int64*)&a);
        i = IPAddress.HostToNetworkOrder(i);
        return *((UInt64*)&i);
    }
    

    2. What about floating point numbers (single and double). I think no, however If I do need to should I do a similar method to the unsigned ints and cast a single pointer into a int pointer and convert like so?

EDIT:: Jons answer doesn't answer the second half of the question (it doesn't really answer the first either!), I would appreciate someone answering part 2

Upvotes: 0

Views: 1137

Answers (2)

Lex Li
Lex Li

Reputation: 63243

You'd better read several RFC documents to see how different TCP/IP protocols (application level, for example, HTTP/FTP/SNMP and so on).

This is generally speaking, a protocol specific question (both your questions), as your packet must encapsulate the integers or floating point number in a protocol defined format.

For SNMP, this is a conversion that changing an integer/float number to a few bytes and changing it back. ASN.1 is used.

http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1502036

I suspect you'd find it easier to use my EndianBinaryReader and EndianBinaryWriter in MiscUtil - then you can decide the endianness yourself. Alternatively, for individual values, you can use EndianBitConverter.

Upvotes: 1

Related Questions