IPv6Address.cs 9.7 KB

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