IPv6Address.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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. bool ipv6 = false;
  145. for (int i = 0; i < len; i++) {
  146. string piece = pieces [i];
  147. if (piece == "!")
  148. piecedouble = i;
  149. else {
  150. int plen = piece.Length;
  151. if (plen > 4)
  152. throw new FormatException ("Not a valid IPv6 address");
  153. int p = 0;
  154. for (int j = 0; j < plen; j++)
  155. try {
  156. p = (p << 4) + Uri.FromHex (piece [j]);
  157. } catch (ArgumentException) {
  158. throw new FormatException ("Not a valid IPv6 address");
  159. }
  160. addr [i] = (ushort) p;
  161. if (p != 0 || (i == 5 && p != 0xffff))
  162. ipv6 = true;
  163. }
  164. }
  165. //expand the :: token
  166. if (piecedouble != -1) {
  167. int totallen = (ipv4 ? 5 : 7);
  168. int i = totallen;
  169. for (i = totallen; i >= (totallen - (len - piecedouble - 1)); i--) {
  170. addr [i] = addr [(len - 1) + i - totallen];
  171. }
  172. for (; i >= piecedouble; i--) {
  173. addr [i] = 0;
  174. }
  175. } else if (len != (ipv4 ? 6 : 8))
  176. throw new FormatException ("Not a valid IPv6 address");
  177. // check IPv4 validity
  178. if (ipv4 && !ipv6) {
  179. for (int i = 0; i < 5; i++) {
  180. if (addr [i] != 0)
  181. throw new FormatException ("Not a valid IPv6 address");
  182. }
  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. public static bool IsLoopback (IPv6Address addr)
  209. {
  210. if (addr.address [7] != 1)
  211. return false;
  212. int x = addr.address [6] >> 8;
  213. if (x != 0x7f && x != 0)
  214. return false;
  215. for (int i = 0; i < 4; i++) {
  216. if (addr.address [i] != 0)
  217. return false;
  218. }
  219. if (addr.address [5] != 0 && addr.address [5] != 0xffff)
  220. return false;
  221. return true;
  222. }
  223. private static ushort SwapUShort (ushort number)
  224. {
  225. return (ushort) ( ((number >> 8) & 0xFF) + ((number << 8) & 0xFF00) );
  226. }
  227. // Convert the address into a format expected by the IPAddress (long) ctor
  228. private int AsIPv4Int ()
  229. {
  230. return (SwapUShort (address [7]) << 16) + SwapUShort (address [6]);
  231. }
  232. public bool IsIPv4Compatible ()
  233. {
  234. for (int i = 0; i < 6; i++)
  235. if (address [i] != 0)
  236. return false;
  237. return (AsIPv4Int () > 1);
  238. }
  239. public bool IsIPv4Mapped ()
  240. {
  241. for (int i = 0; i < 5; i++)
  242. if (address [i] != 0)
  243. return false;
  244. return address [5] == 0xffff;
  245. }
  246. /// <summary>
  247. /// Overrides System.Object.ToString to return
  248. /// this object rendered in a canonicalized notation
  249. /// </summary>
  250. public override string ToString ()
  251. {
  252. StringBuilder s = new StringBuilder ();
  253. if(IsIPv4Compatible() || IsIPv4Mapped())
  254. {
  255. s.Append("::");
  256. if(IsIPv4Mapped())
  257. s.Append("ffff:");
  258. s.Append(new IPAddress( AsIPv4Int ()).ToString ());
  259. return s.ToString ();
  260. }
  261. else
  262. {
  263. int bestChStart = -1; // Best chain start
  264. int bestChLen = 0; // Best chain length
  265. int currChLen = 0; // Current chain length
  266. // Looks for the longest zero chain
  267. for (int i=0; i<8; i++)
  268. {
  269. if (address[i] != 0)
  270. {
  271. if ((currChLen > bestChLen)
  272. && (currChLen > 1))
  273. {
  274. bestChLen = currChLen;
  275. bestChStart = i - currChLen;
  276. }
  277. currChLen = 0;
  278. }
  279. else
  280. currChLen++;
  281. }
  282. if ((currChLen > bestChLen)
  283. && (currChLen > 1))
  284. {
  285. bestChLen = currChLen;
  286. bestChStart = 8 - currChLen;
  287. }
  288. // makes the string
  289. if (bestChStart == 0)
  290. s.Append(":");
  291. for (int i=0; i<8; i++)
  292. {
  293. if (i == bestChStart)
  294. {
  295. s.Append (":");
  296. i += (bestChLen - 1);
  297. continue;
  298. }
  299. s.AppendFormat("{0:x}", address [i]);
  300. if (i < 7) s.Append (':');
  301. }
  302. }
  303. return s.ToString ();
  304. }
  305. /// <returns>
  306. /// Whether both objects are equal.
  307. /// </returns>
  308. public override bool Equals (object other)
  309. {
  310. System.Net.IPv6Address ipv6 = other as System.Net.IPv6Address;
  311. if (ipv6 != null) {
  312. for (int i = 0; i < 8; i++)
  313. if (this.address [i] != ipv6.address [i])
  314. return false;
  315. return true;
  316. }
  317. System.Net.IPAddress ipv4 = other as System.Net.IPAddress;
  318. if (ipv4 != null) {
  319. for (int i = 0; i < 5; i++)
  320. if (address [i] != 0)
  321. return false;
  322. if (address [5] != 0 && address [5] != 0xffff)
  323. return false;
  324. long a = ipv4.InternalIPv4Address;
  325. if (address [6] != (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff))) ||
  326. address [7] != (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff))))
  327. return false;
  328. return true;
  329. }
  330. return false;
  331. }
  332. public override int GetHashCode ()
  333. {
  334. return Hash (((((int) address [0]) << 16) + address [1]),
  335. ((((int) address [2]) << 16) + address [3]),
  336. ((((int) address [4]) << 16) + address [5]),
  337. ((((int) address [6]) << 16) + address [7]));
  338. }
  339. private static int Hash (int i, int j, int k, int l)
  340. {
  341. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  342. }
  343. }
  344. }