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.

3
  • 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. Commented Jun 5, 2020 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. github.com/microsoft/referencesource/blob/… Commented Jun 5, 2020 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. Commented Jun 5, 2020 at 22:49

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the link helps. Still not sure why one of the two statements didn't give me a 1, as in swapping 1.0.0.0 for 0.0.0.1. or vice versa.
You passed 0.0.0.1 in both cases. And in both cases it reversed the byte order to 1.0.0.0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.