IPv6Address.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. //
  2. // System.Net.IPv6Address.cs
  3. //
  4. // Author:
  5. // Lawrence Pit ([email protected])
  6. //
  7. // Note I: This class is not defined in the specs of .Net
  8. //
  9. // Note II : The name of this class is perhaps unfortunate as it turns
  10. // out that in ms.net there's an internal class called
  11. // IPv6Address in namespace System.
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.Net.Sockets;
  35. using System.Runtime.InteropServices;
  36. using System.Text;
  37. namespace System.Net {
  38. /// <remarks>
  39. /// Encapsulates an IPv6 Address.
  40. /// See RFC 2373 for more info on IPv6 addresses.
  41. /// </remarks>
  42. [Serializable]
  43. internal class IPv6Address {
  44. private ushort [] address;
  45. private int prefixLength;
  46. private long scopeId = 0;
  47. public static readonly IPv6Address Loopback = IPv6Address.Parse ("::1");
  48. public static readonly IPv6Address Unspecified = IPv6Address.Parse ("::");
  49. public IPv6Address (ushort [] addr)
  50. {
  51. if (addr == null)
  52. throw new ArgumentNullException ("addr");
  53. if (addr.Length != 8)
  54. throw new ArgumentException ("addr");
  55. address = addr;
  56. }
  57. public IPv6Address (ushort [] addr, int prefixLength) : this (addr)
  58. {
  59. if (prefixLength < 0 || prefixLength > 128)
  60. throw new ArgumentException ("prefixLength");
  61. this.prefixLength = prefixLength;
  62. }
  63. public IPv6Address (ushort [] addr, int prefixLength, int scopeId) : this (addr, prefixLength)
  64. {
  65. this.scopeId = scopeId;
  66. }
  67. public static IPv6Address Parse (string ipString)
  68. {
  69. if (ipString == null)
  70. throw new ArgumentNullException ("ipString");
  71. if (ipString.Length > 2 &&
  72. ipString [0] == '[' &&
  73. ipString [ipString.Length - 1] == ']')
  74. ipString = ipString.Substring (1, ipString.Length - 2);
  75. if (ipString.Length < 2)
  76. throw new FormatException ("Not a valid IPv6 address");
  77. int prefixLen = 0;
  78. int scopeId = 0;
  79. int pos = ipString.LastIndexOf ('/');
  80. if (pos != -1) {
  81. string prefix = ipString.Substring (pos + 1);
  82. try {
  83. prefixLen = Int32.Parse (prefix);
  84. } catch (Exception) {
  85. prefixLen = -1;
  86. }
  87. if (prefixLen < 0 || prefixLen > 128)
  88. throw new FormatException ("Not a valid prefix length");
  89. ipString = ipString.Substring (0, pos);
  90. } else {
  91. pos = ipString.LastIndexOf ('%');
  92. if (pos != -1) {
  93. string prefix = ipString.Substring (pos + 1);
  94. try {
  95. scopeId = Int32.Parse (prefix);
  96. }
  97. catch (Exception) {
  98. scopeId = 0;
  99. }
  100. ipString = ipString.Substring (0, pos);
  101. }
  102. }
  103. ushort [] addr = new ushort [8];
  104. bool ipv4 = false;
  105. int pos2 = ipString.LastIndexOf (":");
  106. if (pos2 == -1)
  107. throw new FormatException ("Not a valid IPv6 address");
  108. if (pos2 < (ipString.Length - 1)) {
  109. string ipv4Str = ipString.Substring (pos2 + 1);
  110. if (ipv4Str.IndexOf ('.') != -1) {
  111. try {
  112. long a = IPAddress.Parse (ipv4Str).InternalIPv4Address;
  113. addr [6] = (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff)));
  114. addr [7] = (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff)));
  115. if (ipString [pos2 - 1] == ':')
  116. ipString = ipString.Substring (0, pos2 + 1);
  117. else
  118. ipString = ipString.Substring (0, pos2);
  119. ipv4 = true;
  120. } catch (Exception) {
  121. throw new FormatException ("Not a valid IPv6 address");
  122. }
  123. }
  124. }
  125. int origLen = ipString.Length;
  126. if (origLen < 2)
  127. throw new FormatException ("Not a valid IPv6 address");
  128. ipString = ipString.Replace ("::", ":!:");
  129. int len = ipString.Length;
  130. if ((len - origLen) > 1)
  131. throw new FormatException ("Not a valid IPv6 address");
  132. if (ipString [1] == '!')
  133. ipString = ipString.Remove (0, 1);
  134. if (ipString [len - 2] == '!')
  135. ipString = ipString.Remove (len - 1, 1);
  136. if ((ipString.Length > 2) &&
  137. ((ipString [0] == ':') || (ipString [ipString.Length - 1] == ':')))
  138. throw new FormatException ("Not a valid IPv6 address");
  139. string [] pieces = ipString.Split (new char [] {':'});
  140. len = pieces.Length;
  141. if (len > (ipv4 ? 6 : 8))
  142. throw new FormatException ("Not a valid IPv6 address");
  143. int piecedouble = -1;
  144. for (int i = 0; i < len; i++) {
  145. string piece = pieces [i];
  146. if (piece == "!")
  147. piecedouble = i;
  148. else {
  149. int plen = piece.Length;
  150. if (plen > 4)
  151. throw new FormatException ("Not a valid IPv6 address");
  152. int p = 0;
  153. for (int j = 0; j < plen; j++)
  154. try {
  155. p = (p << 4) + Uri.FromHex (piece [j]);
  156. } catch (ArgumentException) {
  157. throw new FormatException ("Not a valid IPv6 address");
  158. }
  159. addr [i] = (ushort) p;
  160. }
  161. }
  162. //expand the :: token
  163. if (piecedouble != -1) {
  164. int totallen = (ipv4 ? 5 : 7);
  165. int i = totallen;
  166. for (i = totallen; i >= (totallen - (len - piecedouble - 1)); i--) {
  167. addr [i] = addr [(len - 1) + i - totallen];
  168. }
  169. for (; i >= piecedouble; i--) {
  170. addr [i] = 0;
  171. }
  172. } else if (len != (ipv4 ? 6 : 8))
  173. throw new FormatException ("Not a valid IPv6 address");
  174. // check IPv4 validity
  175. if (ipv4) {
  176. for (int i = 0; i < 5; i++)
  177. if (addr [i] != 0)
  178. throw new FormatException ("Not a valid IPv6 address");
  179. if (addr [5] != 0 && addr [5] != 0xffff)
  180. throw new FormatException ("Not a valid IPv6 address");
  181. }
  182. return new IPv6Address (addr, prefixLen, scopeId);
  183. }
  184. public ushort [] Address {
  185. get { return address; }
  186. }
  187. public int PrefixLength {
  188. get { return this.prefixLength; }
  189. }
  190. public long ScopeId {
  191. get {
  192. return scopeId;
  193. }
  194. set {
  195. scopeId = value;
  196. }
  197. }
  198. public ushort this [int index] {
  199. get { return address [index]; }
  200. }
  201. public AddressFamily AddressFamily {
  202. get { return AddressFamily.InterNetworkV6; }
  203. }
  204. /// <summary>
  205. /// Used to tell whether the given address is the loopback address.
  206. /// </summary>
  207. public static bool IsLoopback (IPv6Address addr)
  208. {
  209. for (int i = 0; i < 4; i++)
  210. if (addr.address [i] != 0)
  211. return false;
  212. if ((addr.address [5] != 0) && (addr.address [5] != 0xffff))
  213. return false;
  214. if ((addr.address [6] >> 8) == 0x7f)
  215. return true;
  216. return ((addr.address [5] == 0) &&
  217. (addr.address [6] == 0) &&
  218. (addr.address [7] == 1));
  219. }
  220. private static ushort SwapUShort (ushort number)
  221. {
  222. return (ushort) ( ((number >> 8) & 0xFF) + ((number << 8) & 0xFF00) );
  223. }
  224. // Convert the address into a format expected by the IPAddress (long) ctor
  225. private int AsIPv4Int ()
  226. {
  227. return (SwapUShort (address [7]) << 16) + SwapUShort (address [6]);
  228. }
  229. public bool IsIPv4Compatible ()
  230. {
  231. for (int i = 0; i < 6; i++)
  232. if (address [i] != 0)
  233. return false;
  234. return (AsIPv4Int () > 1);
  235. }
  236. public bool IsIPv4Mapped ()
  237. {
  238. for (int i = 0; i < 5; i++)
  239. if (address [i] != 0)
  240. return false;
  241. return address [5] == 0xffff;
  242. }
  243. /// <summary>
  244. /// Overrides System.Object.ToString to return
  245. /// this object rendered in a canonicalized notation
  246. /// </summary>
  247. public override string ToString ()
  248. {
  249. StringBuilder s = new StringBuilder ();
  250. if(IsIPv4Compatible() || IsIPv4Mapped())
  251. {
  252. s.Append("::");
  253. if(IsIPv4Mapped())
  254. s.Append("ffff:");
  255. s.Append(new IPAddress( AsIPv4Int ()).ToString ());
  256. return s.ToString ();
  257. }
  258. else
  259. {
  260. int bestChStart = -1; // Best chain start
  261. int bestChLen = 0; // Best chain length
  262. int currChLen = 0; // Current chain length
  263. // Looks for the longest zero chain
  264. for (int i=0; i<8; i++)
  265. {
  266. if (address[i] != 0)
  267. {
  268. if ((currChLen > bestChLen)
  269. && (currChLen > 1))
  270. {
  271. bestChLen = currChLen;
  272. bestChStart = i - currChLen;
  273. }
  274. currChLen = 0;
  275. }
  276. else
  277. currChLen++;
  278. }
  279. if ((currChLen > bestChLen)
  280. && (currChLen > 1))
  281. {
  282. bestChLen = currChLen;
  283. bestChStart = 8 - currChLen;
  284. }
  285. // makes the string
  286. if (bestChStart == 0)
  287. s.Append(":");
  288. for (int i=0; i<8; i++)
  289. {
  290. if (i == bestChStart)
  291. {
  292. s.Append (":");
  293. i += (bestChLen - 1);
  294. continue;
  295. }
  296. s.AppendFormat("{0:x}", address [i]);
  297. if (i < 7) s.Append (':');
  298. }
  299. }
  300. return s.ToString ();
  301. }
  302. /// <returns>
  303. /// Whether both objects are equal.
  304. /// </returns>
  305. public override bool Equals (object other)
  306. {
  307. System.Net.IPv6Address ipv6 = other as System.Net.IPv6Address;
  308. if (ipv6 != null) {
  309. for (int i = 0; i < 8; i++)
  310. if (this.address [i] != ipv6.address [i])
  311. return false;
  312. return true;
  313. }
  314. System.Net.IPAddress ipv4 = other as System.Net.IPAddress;
  315. if (ipv4 != null) {
  316. for (int i = 0; i < 5; i++)
  317. if (address [i] != 0)
  318. return false;
  319. if (address [5] != 0 && address [5] != 0xffff)
  320. return false;
  321. long a = ipv4.InternalIPv4Address;
  322. if (address [6] != (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff))) ||
  323. address [7] != (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff))))
  324. return false;
  325. return true;
  326. }
  327. return false;
  328. }
  329. public override int GetHashCode ()
  330. {
  331. return Hash (((((int) address [0]) << 16) + address [1]),
  332. ((((int) address [2]) << 16) + address [3]),
  333. ((((int) address [4]) << 16) + address [5]),
  334. ((((int) address [6]) << 16) + address [7]));
  335. }
  336. private static int Hash (int i, int j, int k, int l)
  337. {
  338. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  339. }
  340. }
  341. }