Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I use the following method for converting an IP address to two <code>UInt64</code>s (C# 3.0).</p> <pre><code>/// &lt;summary&gt; /// Converts an IP address to its UInt64[2] equivalent. /// For an IPv4 address, the first element will be 0, /// and the second will be a UInt32 representation of the four bytes. /// For an IPv6 address, the first element will be a UInt64 /// representation of the first eight bytes, and the second will be the /// last eight bytes. /// &lt;/summary&gt; /// &lt;param name="ipAddress"&gt;The IP address to convert.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static ulong[] ConvertIPAddressToUInt64Array(string ipAddress) { byte[] addrBytes = System.Net.IPAddress.Parse(ipAddress).GetAddressBytes(); if (System.BitConverter.IsLittleEndian) { //little-endian machines store multi-byte integers with the //least significant byte first. this is a problem, as integer //values are sent over the network in big-endian mode. reversing //the order of the bytes is a quick way to get the BitConverter //methods to convert the byte arrays in big-endian mode. System.Collections.Generic.List&lt;byte&gt; byteList = new System.Collections.Generic.List&lt;byte&gt;(addrBytes); byteList.Reverse(); addrBytes = byteList.ToArray(); } ulong[] addrWords = new ulong[2]; if (addrBytes.Length &gt; 8) { addrWords[0] = System.BitConverter.ToUInt64(addrBytes, 8); addrWords[1] = System.BitConverter.ToUInt64(addrBytes, 0); } else { addrWords[0] = 0; addrWords[1] = System.BitConverter.ToUInt32(addrBytes, 0); } return addrWords; } </code></pre> <p>Make sure you cast your <code>UInt64</code>s to <code>Int64</code>s before you put them into the database, or you'll get an <code>ArgumentException</code>. When you get your values back out, you can cast them back to <code>UInt64</code> to get the unsigned value.</p> <p>I don't have a need to do the reverse (i.e. convert a <code>UInt64[2]</code> to an IP string) so I never built a method for it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload