Reputation: 568
In .NET IPAddress.HostToNetworkOrder() can only take in a long int (64-bit) and return a long. This is fine for IPv4, but IPv6 addresses are 128-bit. The only way I have found to store an IPv6 address as an integer is to do this:
BigInteger big = new BigInteger(ip.GetAddressBytes());
How can I convert from Host Order to Network order using BigInteger/IPv6 addresses?
Upvotes: 2
Views: 2043
Reputation: 568
I figured it out!
IPAddress ip = IPAddress.Parse("{IP ADDRESS}");
List<Byte> ipFormat = ip.GetAddressBytes().ToList();
ipFormat.Reverse();
ipFormat.Add(0);
BigInteger ipAsInt = new BigInteger(ipFormat.ToArray());
Upvotes: 2
Reputation: 22261
The purpose of converting an IP address to host byte order is so that you can do arithmetic on it using the CPU's normal integer types. For example, in IPv4:
network_base_address = address & (0xffffffff ^ ((1 << (32-prefix_length)) - 1)
Due to the large size of IPv6 addresses and the rarity of CPU native types that are that big, it was not expected that this kind of arithmetic would be performed on IPv6 addresses.
Instead, you can manipulate the original IP address (in network byte order) stored as an array of 16 bytes. For example, while the usual implementation of the C macro IN_MULTICAST
(for IPv4) works by bitmasking the integer value of the IP address, the usual implementation of the C macro IN6_IS_ADDR_MULTICAST
does its job not by treating the IP address as an integer, but by examining the first byte of the IP address as found in a byte array. (I know this information is for C and your question is about C#, but it's the same idea).
Upvotes: 2