IPv6Address.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. /// <summary>
  50. /// Constructor from a 32-bit constant with its bytes
  51. /// in network order.
  52. /// </summary>
  53. public IPv6Address (ushort [] addr)
  54. {
  55. if (addr == null)
  56. throw new ArgumentNullException ("addr");
  57. if (addr.Length != 8)
  58. throw new ArgumentException ("addr");
  59. address = addr;
  60. }
  61. public IPv6Address (ushort [] addr, int prefixLength) : this (addr)
  62. {
  63. if (prefixLength < 0 || prefixLength > 128)
  64. throw new ArgumentException ("prefixLength");
  65. this.prefixLength = prefixLength;
  66. }
  67. public IPv6Address (ushort [] addr, int prefixLength, int scopeId) : this (addr, prefixLength)
  68. {
  69. this.scopeId = scopeId;
  70. }
  71. public static IPv6Address Parse (string ipString)
  72. {
  73. if (ipString == null)
  74. throw new ArgumentNullException ("ipString");
  75. if (ipString.Length > 2 &&
  76. ipString [0] == '[' &&
  77. ipString [ipString.Length - 1] == ']')
  78. ipString = ipString.Substring (1, ipString.Length - 2);
  79. if (ipString.Length < 2)
  80. throw new FormatException ("Not a valid IPv6 address");
  81. int prefixLen = 0;
  82. int scopeId = 0;
  83. int pos = ipString.LastIndexOf ('/');
  84. if (pos != -1) {
  85. string prefix = ipString.Substring (pos + 1);
  86. try {
  87. prefixLen = Int32.Parse (prefix);
  88. } catch (Exception) {
  89. prefixLen = -1;
  90. }
  91. if (prefixLen < 0 || prefixLen > 128)
  92. throw new FormatException ("Not a valid prefix length");
  93. ipString = ipString.Substring (0, pos);
  94. } else {
  95. pos = ipString.LastIndexOf ('%');
  96. if (pos != -1) {
  97. string prefix = ipString.Substring (pos + 1);
  98. try {
  99. scopeId = Int32.Parse (prefix);
  100. }
  101. catch (Exception) {
  102. scopeId = 0;
  103. }
  104. ipString = ipString.Substring (0, pos);
  105. }
  106. }
  107. ushort [] addr = new ushort [8];
  108. bool ipv4 = false;
  109. int pos2 = ipString.LastIndexOf (":");
  110. if (pos2 == -1)
  111. throw new FormatException ("Not a valid IPv6 address");
  112. if (pos2 < (ipString.Length - 1)) {
  113. string ipv4Str = ipString.Substring (pos2 + 1);
  114. if (ipv4Str.IndexOf ('.') != -1) {
  115. try {
  116. long a = IPAddress.Parse (ipv4Str).InternalIPv4Address;
  117. addr [6] = (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff)));
  118. addr [7] = (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff)));
  119. if (ipString [pos2 - 1] == ':')
  120. ipString = ipString.Substring (0, pos2 + 1);
  121. else
  122. ipString = ipString.Substring (0, pos2);
  123. ipv4 = true;
  124. } catch (Exception) {
  125. throw new FormatException ("Not a valid IPv6 address");
  126. }
  127. }
  128. }
  129. int origLen = ipString.Length;
  130. if (origLen < 2)
  131. throw new FormatException ("Not a valid IPv6 address");
  132. ipString = ipString.Replace ("::", ":!:");
  133. int len = ipString.Length;
  134. if ((len - origLen) > 1)
  135. throw new FormatException ("Not a valid IPv6 address");
  136. if (ipString [1] == '!')
  137. ipString = ipString.Remove (0, 1);
  138. if (ipString [len - 2] == '!')
  139. ipString = ipString.Remove (len - 1, 1);
  140. if ((ipString.Length > 2) &&
  141. ((ipString [0] == ':') || (ipString [ipString.Length - 1] == ':')))
  142. throw new FormatException ("Not a valid IPv6 address");
  143. string [] pieces = ipString.Split (new char [] {':'});
  144. len = pieces.Length;
  145. if (len > (ipv4 ? 6 : 8))
  146. throw new FormatException ("Not a valid IPv6 address");
  147. int piecedouble = -1;
  148. for (int i = 0; i < len; i++) {
  149. string piece = pieces [i];
  150. if (piece == "!")
  151. piecedouble = i;
  152. else {
  153. int plen = piece.Length;
  154. if (plen > 4)
  155. throw new FormatException ("Not a valid IPv6 address");
  156. int p = 0;
  157. for (int j = 0; j < plen; j++)
  158. try {
  159. p = (p << 4) + Uri.FromHex (piece [j]);
  160. } catch (ArgumentException) {
  161. throw new FormatException ("Not a valid IPv6 address");
  162. }
  163. addr [i] = (ushort) p;
  164. }
  165. }
  166. //expand the :: token
  167. if (piecedouble != -1) {
  168. int totallen = (ipv4 ? 5 : 7);
  169. int i = totallen;
  170. for (i = totallen; i >= (totallen - (len - piecedouble - 1)); i--) {
  171. addr [i] = addr [(len - 1) + i - totallen];
  172. }
  173. for (; i >= piecedouble; i--) {
  174. addr [i] = 0;
  175. }
  176. } else if (len != (ipv4 ? 6 : 8))
  177. throw new FormatException ("Not a valid IPv6 address");
  178. // check IPv4 validity
  179. if (ipv4) {
  180. for (int i = 0; i < 5; i++)
  181. if (addr [i] != 0)
  182. throw new FormatException ("Not a valid IPv6 address");
  183. if (addr [5] != 0 && addr [5] != 0xffff)
  184. throw new FormatException ("Not a valid IPv6 address");
  185. }
  186. return new IPv6Address (addr, prefixLen, scopeId);
  187. }
  188. public ushort [] Address {
  189. get { return address; }
  190. }
  191. public int PrefixLength {
  192. get { return this.prefixLength; }
  193. }
  194. public long ScopeId {
  195. get {
  196. return scopeId;
  197. }
  198. set {
  199. scopeId = value;
  200. }
  201. }
  202. public ushort this [int index] {
  203. get { return address [index]; }
  204. }
  205. public AddressFamily AddressFamily {
  206. get { return AddressFamily.InterNetworkV6; }
  207. }
  208. /// <summary>
  209. /// Used to tell whether the given address is the loopback address.
  210. /// </summary>
  211. public static bool IsLoopback (IPv6Address addr)
  212. {
  213. for (int i = 0; i < 4; i++)
  214. if (addr.address [i] != 0)
  215. return false;
  216. if ((addr.address [5] != 0) && (addr.address [5] != 0xffff))
  217. return false;
  218. if ((addr.address [6] >> 8) == 0x7f)
  219. return true;
  220. return ((addr.address [5] == 0) &&
  221. (addr.address [6] == 0) &&
  222. (addr.address [7] == 1));
  223. }
  224. public bool IsIPv4Compatible ()
  225. {
  226. for (int i = 0; i < 6; i++)
  227. if (address [i] != 0)
  228. return false;
  229. return ( (IPAddress.NetworkToHostOrder(address[7]) << 16) | IPAddress.NetworkToHostOrder(address[6])) > 1;
  230. }
  231. public bool IsIPv4Mapped ()
  232. {
  233. for (int i = 0; i < 5; i++)
  234. if (address [i] != 0)
  235. return false;
  236. return address [5] == 0xffff;
  237. }
  238. /// <summary>
  239. /// Overrides System.Object.ToString to return
  240. /// this object rendered in a canonicalized notation
  241. /// </summary>
  242. public override string ToString ()
  243. {
  244. StringBuilder s = new StringBuilder ();
  245. if(IsIPv4Compatible() || IsIPv4Mapped())
  246. {
  247. s.Append("::");
  248. if(IsIPv4Mapped())
  249. s.Append("ffff:");
  250. s.Append(new IPAddress( IPAddress.NetworkToHostOrder(address[6]<<16) + IPAddress.NetworkToHostOrder(address[7])).ToString());
  251. return s.ToString ();
  252. }
  253. else
  254. {
  255. int bestChStart = -1; // Best chain start
  256. int bestChLen = 0; // Best chain length
  257. int currChLen = 0; // Current chain length
  258. // Looks for the longest zero chain
  259. for (int i=0; i<8; i++)
  260. {
  261. if (address[i] != 0)
  262. {
  263. if ((currChLen > bestChLen)
  264. && (currChLen > 1))
  265. {
  266. bestChLen = currChLen;
  267. bestChStart = i - currChLen;
  268. }
  269. currChLen = 0;
  270. }
  271. else
  272. currChLen++;
  273. }
  274. if ((currChLen > bestChLen)
  275. && (currChLen > 1))
  276. {
  277. bestChLen = currChLen;
  278. bestChStart = 8 - currChLen;
  279. }
  280. // makes the string
  281. if (bestChStart == 0)
  282. s.Append(":");
  283. for (int i=0; i<8; i++)
  284. {
  285. if (i == bestChStart)
  286. {
  287. s.Append (":");
  288. i += (bestChLen - 1);
  289. continue;
  290. }
  291. s.AppendFormat("{0:x}", address [i]);
  292. if (i < 7) s.Append (':');
  293. }
  294. }
  295. return s.ToString ();
  296. }
  297. /// <returns>
  298. /// Whether both objects are equal.
  299. /// </returns>
  300. public override bool Equals (object other)
  301. {
  302. System.Net.IPv6Address ipv6 = other as System.Net.IPv6Address;
  303. if (ipv6 != null) {
  304. for (int i = 0; i < 8; i++)
  305. if (this.address [i] != ipv6.address [i])
  306. return false;
  307. return true;
  308. }
  309. System.Net.IPAddress ipv4 = other as System.Net.IPAddress;
  310. if (ipv4 != null) {
  311. for (int i = 0; i < 5; i++)
  312. if (address [i] != 0)
  313. return false;
  314. if (address [5] != 0 && address [5] != 0xffff)
  315. return false;
  316. long a = ipv4.InternalIPv4Address;
  317. if (address [6] != (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff))) ||
  318. address [7] != (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff))))
  319. return false;
  320. return true;
  321. }
  322. return false;
  323. }
  324. public override int GetHashCode ()
  325. {
  326. return Hash (((((int) address [0]) << 16) + address [1]),
  327. ((((int) address [2]) << 16) + address [3]),
  328. ((((int) address [4]) << 16) + address [5]),
  329. ((((int) address [6]) << 16) + address [7]));
  330. }
  331. private static int Hash (int i, int j, int k, int l)
  332. {
  333. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  334. }
  335. }
  336. }