2

Sorry to ask about what should be a simple thing, but I've been trying to use IPAddress.NetworkToHostOrder and IPAddress.HostToNetworkOrder to no avail. I'm on Windows rig, little endian. Here's tiny code for what's puzzling me:

using System;
using System.Net;

public class Program
{
    public static void Main()
    {
        int addr = 1;
        Console.WriteLine($"{IPAddress.NetworkToHostOrder(addr)}");
        Console.WriteLine($"{IPAddress.HostToNetworkOrder(addr)}");
    }
}

The output for this is:

16777216
16777216

The output for one of these should be 1, right? I've given up, and wrote a replacement to handle the byte sequencing issue, but it's driving me nuts that I haven't been able to use IPaddress for this.

  • 1
    No, that's a brain-bug. Network order is always big-endian, host order is always little-endian on your machine. So any conversion from one to the other must reverse the byte order. Assuming that `int addr=1` represents the same ip address either way is not correct. – Hans Passant Jun 05 '20 at 22:16
  • 1
    If you look at the implementation, `NetworkToHostOrder` simply calls `HostToNetworkOrder`. On BigEndian *compilations* it always returns the value passed in, otherwise it does some computation. https://github.com/microsoft/referencesource/blob/a7bd3242bd7732dec4aebb21fbc0f6de61c2545e/System/net/System/Net/IPAddress.cs#L516 – pinkfloydx33 Jun 05 '20 at 22:17
  • Hans Passant, 1 represents 0.0.0.1. If the byte storage is swapped, the integer value is 16777216. But I think I see where I confused things, pinkfloydx33 comment and link above is helpful. – slackpatrol Jun 05 '20 at 22:49

1 Answers1

2

Those functions assume that you've provided an input value in a given byte order and always want to swap the byte order to the opposite byte order. They have no way of knowing the byte order of the value you've provided. So, they both always swap the order of what's given to them.

As indicated in this answer, one reason that both functions exist is to serve as documentation and indicate which order (host vs network) you're going from/to.

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328