Convert an IP Address to an Integer in C# in host byte ordering

Yesterday I wrote about converting an IP Address to an Integer in C#. But both methods I presented return the IP Address in network byte order.

However in some cases, especially when calling WinApi functions, you will need to convert the Integer to host byte order which is little-endian on Intel processors.

In an unmanaged language we could do very fast byte swap with inline assembly, eg:

From WinApi we could use the ntohl function and in managed languages we can use the NetworkToHostOrder method from the System.Net.IPAddress class.

For an IPv4 address we need to make sure we are using the proper overload by casting the result of System.BitConverter to an int:

Leave a Reply