IPv6Address.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. public class IPv6Address {
  24. private ushort [] address;
  25. private int prefixLength;
  26. public static readonly IPv6Address Loopback = IPv6Address.Parse ("::1");
  27. public static readonly IPv6Address Unspecified = IPv6Address.Parse ("::");
  28. /// <summary>
  29. /// Constructor from a 32-bit constant with its bytes
  30. /// in network order.
  31. /// </summary>
  32. public IPv6Address (ushort [] addr)
  33. {
  34. if (addr == null)
  35. throw new ArgumentNullException ("addr");
  36. if (addr.Length != 8)
  37. throw new ArgumentException ("addr");
  38. address = addr;
  39. }
  40. public IPv6Address (ushort [] addr, int prefixLength) : this (addr)
  41. {
  42. if (prefixLength < 0 || prefixLength > 128)
  43. throw new ArgumentException ("prefixLength");
  44. this.prefixLength = prefixLength;
  45. }
  46. public static IPv6Address Parse (string ipString)
  47. {
  48. if (ipString == null)
  49. throw new ArgumentNullException ("ipString");
  50. if (ipString.Length > 2 &&
  51. ipString [0] == '[' &&
  52. ipString [ipString.Length - 1] == ']')
  53. ipString = ipString.Substring (1, ipString.Length - 2);
  54. if (ipString.Length < 2)
  55. throw new FormatException ("Not a valid IPv6 address");
  56. int prefixLen = 0;
  57. int pos = ipString.LastIndexOf ('/');
  58. if (pos != -1) {
  59. string prefix = ipString.Substring (pos + 1);
  60. try {
  61. prefixLen = Int32.Parse (prefix);
  62. } catch (Exception) {
  63. prefixLen = -1;
  64. }
  65. if (prefixLen < 0 || prefixLen > 128)
  66. throw new FormatException ("Not a valid prefix length");;
  67. ipString = ipString.Substring (0, pos);
  68. }
  69. ushort [] addr = new ushort [8];
  70. bool ipv4 = false;
  71. int pos2 = ipString.LastIndexOf (":");
  72. if (pos2 == -1)
  73. throw new FormatException ("Not a valid IPv6 address");
  74. if (pos2 < (ipString.Length - 1)) {
  75. string ipv4Str = ipString.Substring (pos2 + 1);
  76. if (ipv4Str.IndexOf ('.') != -1) {
  77. try {
  78. long a = IPAddress.Parse (ipv4Str).Address;
  79. addr [6] = (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff)));
  80. addr [7] = (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff)));
  81. if (ipString [pos2 - 1] == ':')
  82. ipString = ipString.Substring (0, pos2 + 1);
  83. else
  84. ipString = ipString.Substring (0, pos2);
  85. ipv4 = true;
  86. } catch (Exception) {
  87. throw new FormatException ("Not a valid IPv6 address");
  88. }
  89. }
  90. }
  91. int origLen = ipString.Length;
  92. if (origLen < 2)
  93. throw new FormatException ("Not a valid IPv6 address");
  94. ipString = ipString.Replace ("::", ":!:");
  95. int len = ipString.Length;
  96. if ((len - origLen) > 1)
  97. throw new FormatException ("Not a valid IPv6 address");
  98. if (ipString [1] == '!')
  99. ipString = ipString.Remove (0, 1);
  100. if (ipString [len - 2] == '!')
  101. ipString = ipString.Remove (len - 1, 1);
  102. if ((ipString.Length > 2) &&
  103. ((ipString [0] == ':') || (ipString [ipString.Length - 1] == ':')))
  104. throw new FormatException ("Not a valid IPv6 address");
  105. string [] pieces = ipString.Split (new char [] {':'});
  106. len = pieces.Length;
  107. if (len > (ipv4 ? 6 : 8))
  108. throw new FormatException ("Not a valid IPv6 address");
  109. int piecedouble = -1;
  110. for (int i = 0; i < len; i++) {
  111. string piece = pieces [i];
  112. if (piece == "!")
  113. piecedouble = i;
  114. else {
  115. int plen = piece.Length;
  116. if (plen > 4)
  117. throw new FormatException ("Not a valid IPv6 address");
  118. int p = 0;
  119. for (int j = 0; j < plen; j++)
  120. try {
  121. p = (p << 4) + Uri.FromHex (piece [j]);
  122. } catch (ArgumentException) {
  123. throw new FormatException ("Not a valid IPv6 address");
  124. }
  125. addr [i] = (ushort) p;
  126. }
  127. }
  128. //expand the :: token
  129. if (piecedouble != -1) {
  130. int totallen = (ipv4 ? 5 : 7);
  131. int i = totallen;
  132. for (i = totallen; i >= (totallen - (len - piecedouble - 1)); i--) {
  133. addr [i] = addr [(len - 1) + i - totallen];
  134. }
  135. for (; i >= piecedouble; i--) {
  136. addr [i] = 0;
  137. }
  138. } else if (len != (ipv4 ? 6 : 8))
  139. throw new FormatException ("Not a valid IPv6 address");
  140. // check IPv4 validity
  141. if (ipv4) {
  142. for (int i = 0; i < 5; i++)
  143. if (addr [i] != 0)
  144. throw new FormatException ("Not a valid IPv6 address");
  145. if (addr [5] != 0 && addr [5] != 0xffff)
  146. throw new FormatException ("Not a valid IPv6 address");
  147. }
  148. return new IPv6Address (addr, prefixLen);
  149. }
  150. public ushort [] Address {
  151. get { return address; }
  152. }
  153. public int PrefixLength {
  154. get { return this.prefixLength; }
  155. }
  156. public ushort this [int index] {
  157. get { return address [index]; }
  158. }
  159. public AddressFamily AddressFamily {
  160. get { return AddressFamily.InterNetworkV6; }
  161. }
  162. /// <summary>
  163. /// Used to tell whether the given address is the loopback address.
  164. /// </summary>
  165. public static bool IsLoopback (IPv6Address addr)
  166. {
  167. for (int i = 0; i < 4; i++)
  168. if (addr.address [i] != 0)
  169. return false;
  170. if ((addr.address [5] != 0) && (addr.address [5] != 0xffff))
  171. return false;
  172. if ((addr.address [6] >> 8) == 0x7f)
  173. return true;
  174. return ((addr.address [5] == 0) &&
  175. (addr.address [6] == 0) &&
  176. (addr.address [7] == 1));
  177. }
  178. public bool IsIPv4Compatible ()
  179. {
  180. for (int i = 0; i < 6; i++)
  181. if (address [i] != 0)
  182. return false;
  183. return true;
  184. }
  185. public bool IsIPv4Mapped ()
  186. {
  187. for (int i = 0; i < 5; i++)
  188. if (address [i] != 0)
  189. return false;
  190. return address [5] == 0xffff;
  191. }
  192. /// <summary>
  193. /// Overrides System.Object.ToString to return
  194. /// this object rendered in a canonicalized notation
  195. /// </summary>
  196. public override string ToString ()
  197. {
  198. StringBuilder s = new StringBuilder ();
  199. for (int i = 0; i < 7; i++)
  200. s.Append (String.Format ("{0:X4}", address [i])).Append (':');
  201. s.Append (String.Format ("{0:X4}", address [7]));
  202. return s.ToString ();
  203. }
  204. /// <returns>
  205. /// Whether both objects are equal.
  206. /// </returns>
  207. public override bool Equals (object other)
  208. {
  209. System.Net.IPv6Address ipv6 = other as System.Net.IPv6Address;
  210. if (ipv6 != null) {
  211. for (int i = 0; i < 8; i++)
  212. if (this.address [i] != ipv6.address [i])
  213. return false;
  214. return true;
  215. }
  216. System.Net.IPAddress ipv4 = other as System.Net.IPAddress;
  217. if (ipv4 != null) {
  218. for (int i = 0; i < 5; i++)
  219. if (address [i] != 0)
  220. return false;
  221. if (address [5] != 0 && address [5] != 0xffff)
  222. return false;
  223. long a = ipv4.Address;
  224. if (address [6] != (ushort) (((int) (a & 0xff) << 8) + ((int) ((a >> 8) & 0xff))) ||
  225. address [7] != (ushort) (((int) ((a >> 16) & 0xff) << 8) + ((int) ((a >> 24) & 0xff))))
  226. return false;
  227. return true;
  228. }
  229. return false;
  230. }
  231. public override int GetHashCode ()
  232. {
  233. return Hash (((((int) address [0]) << 16) + address [1]),
  234. ((((int) address [2]) << 16) + address [3]),
  235. ((((int) address [4]) << 16) + address [5]),
  236. ((((int) address [6]) << 16) + address [7]));
  237. }
  238. private static int Hash (int i, int j, int k, int l)
  239. {
  240. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  241. }
  242. }
  243. }