Skip navigation

htons in c#

htonl in c#

HostToNetworkOrder function resides in the System.Net.IPAddress object (what a weird place to put it!)

3 overloads are provided:

System.Net.IPAddress.HostToNetworkOrder( short val )
System.Net.IPAddress.HostToNetworkOrder( int val )
System.Net.IPAddress.HostToNetworkOrder( long val )

Sending binary data in C#

Use the BitConverter class

using System ;
using System.Net ;

class Program
  static void Main( string[] args )
    int val = 0x0112A380 ;
    val = IPAddress.HostToNetworkOrder( val );
    Console.WriteLine("Val is {0}", val ) ;
    Console.WriteLine( "Little endian? " + BitConverter.IsLittleEndian ) ;
    byte[] bytes = BitConverter.GetBytes( val );
    foreach( byte b in bytes )
      Console.WriteLine( b );

One Comment

    • Mattias
    • Posted June 23, 2010 at 1:36 pm
    • Permalink

    Sweet. I’ve been coding servers in c, but have now been asked to do some rapid typing in c#. It is as you said, not the most logical place to put the functions in, but hey, they are there and this page have a good ranking =;OP

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: