IPAddress.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. //
  2. // System.Net.IPAddress.cs
  3. //
  4. // Author:
  5. // Miguel de Icaza ([email protected])
  6. // Lawrence Pit ([email protected])
  7. //
  8. // (C) Ximian, Inc. http://www.ximian.com
  9. //
  10. //
  11. // Note: the address is stored in host order
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Globalization;
  34. using System.Net.Sockets;
  35. using System.Runtime.InteropServices;
  36. namespace System.Net {
  37. /// <remarks>
  38. /// Encapsulates an IP Address.
  39. /// </remarks>
  40. [Serializable]
  41. public class IPAddress {
  42. // Don't change the name of this field without also
  43. // changing socket-io.c in the runtime
  44. private long address;
  45. private AddressFamily _family = AddressFamily.InterNetwork;
  46. private ushort[] _numbers = new ushort[8]; /// ip6 Stored in network order (as ip4)
  47. private long _scopeId = 0;
  48. public static readonly IPAddress Any = new IPAddress(0);
  49. public static readonly IPAddress Broadcast = IPAddress.Parse ("255.255.255.255");
  50. public static readonly IPAddress Loopback = IPAddress.Parse ("127.0.0.1");
  51. public static readonly IPAddress None = IPAddress.Parse ("255.255.255.255");
  52. #if NET_1_1
  53. public static readonly IPAddress IPv6Any = IPAddress.ParseIPV6 ("::");
  54. public static readonly IPAddress IPv6Loopback = IPAddress.ParseIPV6 ("::1");
  55. public static readonly IPAddress IPv6None = IPAddress.ParseIPV6 ("::");
  56. #endif
  57. private static short SwapShort (short number)
  58. {
  59. return (short) ( ((number >> 8) & 0xFF) + ((number << 8) & 0xFF00) );
  60. }
  61. private static int SwapInt (int number)
  62. {
  63. byte b0 = (byte) ((number >> 24) & 0xFF);
  64. byte b1 = (byte) ((number >> 16) & 0xFF);
  65. byte b2 = (byte) ((number >> 8) & 0xFF);
  66. byte b3 = (byte) (number & 0xFF);
  67. return b0 + (b1 << 8) + (b2 << 16) + (b3 << 24);
  68. }
  69. private static long SwapLong (long number)
  70. {
  71. byte b0 = (byte) ((number >> 56) & 0xFF);
  72. byte b1 = (byte) ((number >> 48) & 0xFF);
  73. byte b2 = (byte) ((number >> 40) & 0xFF);
  74. byte b3 = (byte) ((number >> 32) & 0xFF);
  75. byte b4 = (byte) ((number >> 24) & 0xFF);
  76. byte b5 = (byte) ((number >> 16) & 0xFF);
  77. byte b6 = (byte) ((number >> 8) & 0xFF);
  78. byte b7 = (byte) (number & 0xFF);
  79. return (long) b0 + ((long) b1 << 8) + ((long) b2 << 16) + ((long) b3 << 24) + ((long) b4 << 32) + ((long) b5 << 40) + ((long) b6 << 48) + ((long) b7 << 56);
  80. }
  81. public static short HostToNetworkOrder(short host) {
  82. if (!BitConverter.IsLittleEndian)
  83. return(host);
  84. return SwapShort (host);
  85. }
  86. public static int HostToNetworkOrder(int host) {
  87. if (!BitConverter.IsLittleEndian)
  88. return(host);
  89. return SwapInt (host);
  90. }
  91. public static long HostToNetworkOrder(long host) {
  92. if (!BitConverter.IsLittleEndian)
  93. return(host);
  94. return SwapLong (host);
  95. }
  96. public static short NetworkToHostOrder(short network) {
  97. if (!BitConverter.IsLittleEndian)
  98. return(network);
  99. return SwapShort (network);
  100. }
  101. public static int NetworkToHostOrder(int network) {
  102. if (!BitConverter.IsLittleEndian)
  103. return(network);
  104. return SwapInt (network);
  105. }
  106. public static long NetworkToHostOrder(long network) {
  107. if (!BitConverter.IsLittleEndian)
  108. return(network);
  109. return SwapLong (network);
  110. }
  111. /// <summary>
  112. /// Constructor from a 32-bit constant with its bytes
  113. /// in network order.
  114. /// </summary>
  115. public IPAddress (long addr)
  116. {
  117. address = addr;
  118. }
  119. #if NET_1_1
  120. public IPAddress(byte[] address) : this(address, 0)
  121. {
  122. }
  123. public IPAddress(byte[] address, long scopeId)
  124. {
  125. if(address.Length != 16)
  126. throw new ArgumentException("address");
  127. Buffer.BlockCopy(address, 0, _numbers, 0, 16);
  128. _family = AddressFamily.InterNetworkV6;
  129. _scopeId = scopeId;
  130. }
  131. internal IPAddress(ushort[] address, long scopeId)
  132. {
  133. _numbers = address;
  134. for(int i=0; i<8; i++)
  135. _numbers[i] = (ushort)HostToNetworkOrder((short)_numbers[i]);
  136. _family = AddressFamily.InterNetworkV6;
  137. _scopeId = scopeId;
  138. }
  139. #endif
  140. public static IPAddress Parse (string ip)
  141. {
  142. IPAddress ret;
  143. if (ip == null)
  144. throw new ArgumentNullException ("Value cannot be null.");
  145. #if NET_1_1
  146. if( (ret = ParseIPV4(ip)) == null)
  147. if( (ret = ParseIPV6(ip)) == null)
  148. throw new FormatException("An invalid IP address was specified.");
  149. #else
  150. if( (ret = ParseIPV4(ip)) == null)
  151. throw new FormatException("An invalid IP address was specified.");
  152. #endif
  153. return ret;
  154. }
  155. private static IPAddress ParseIPV4 (string ip)
  156. {
  157. if (ip.Length == 0 || ip == " ")
  158. return new IPAddress (0);
  159. int pos = ip.IndexOf (' ');
  160. if (pos != -1)
  161. ip = ip.Substring (0, pos);
  162. if (ip.Length == 0 || ip [ip.Length - 1] == '.')
  163. return null;
  164. string [] ips = ip.Split (new char [] {'.'});
  165. if (ips.Length > 4)
  166. return null;
  167. // Make the number in network order
  168. try
  169. {
  170. long a = 0;
  171. byte val = 0;
  172. for (int i = 0; i < ips.Length; i++) {
  173. string subnet = ips [i];
  174. if ((3 <= subnet.Length && subnet.Length <= 4) &&
  175. (subnet [0] == '0') &&
  176. (subnet [1] == 'x' || subnet [2] == 'X')) {
  177. if (subnet.Length == 3)
  178. val = (byte) Uri.FromHex (subnet [2]);
  179. else
  180. val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
  181. } else if (subnet.Length == 0)
  182. return null;
  183. else
  184. val = Byte.Parse (subnet, NumberStyles.None);
  185. if (ips.Length < 4 && i == (ips.Length - 1))
  186. i = 3;
  187. a |= (long) val << (i << 3);
  188. }
  189. return (new IPAddress (a));
  190. } catch (Exception) {
  191. return null;
  192. }
  193. }
  194. #if NET_1_1
  195. private static IPAddress ParseIPV6 (string ip)
  196. {
  197. try
  198. {
  199. IPv6Address newIPv6Address = IPv6Address.Parse(ip);
  200. return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);
  201. }
  202. catch (Exception) {
  203. return null;
  204. }
  205. }
  206. [Obsolete("This property is obsolete. Use GetAddressBytes.")]
  207. #endif
  208. public long Address
  209. {
  210. get {
  211. if(_family != AddressFamily.InterNetwork)
  212. throw new Exception("The attempted operation is not supported for the type of object referenced");
  213. return address;
  214. }
  215. set {
  216. /* no need to do this test, ms.net accepts any value.
  217. if (value < 0 || value > 0x00000000FFFFFFFF)
  218. throw new ArgumentOutOfRangeException (
  219. "the address must be between 0 and 0xFFFFFFFF");
  220. */
  221. if(_family != AddressFamily.InterNetwork)
  222. throw new Exception("The attempted operation is not supported for the type of object referenced");
  223. address = value;
  224. }
  225. }
  226. internal long InternalIPv4Address {
  227. get { return address; }
  228. }
  229. #if NET_1_1
  230. public long ScopeId {
  231. get {
  232. if(_family != AddressFamily.InterNetworkV6)
  233. throw new Exception("The attempted operation is not supported for the type of object referenced");
  234. return _scopeId;
  235. }
  236. set {
  237. if(_family != AddressFamily.InterNetworkV6)
  238. throw new Exception("The attempted operation is not supported for the type of object referenced");
  239. _scopeId = value;
  240. }
  241. }
  242. public byte [] GetAddressBytes ()
  243. {
  244. if(_family == AddressFamily.InterNetworkV6) {
  245. byte [] addressBytes = new byte [16];
  246. Buffer.BlockCopy (_numbers, 0, addressBytes, 0, 16);
  247. return addressBytes;
  248. } else {
  249. return new byte [4] { (byte)(address & 0xFF),
  250. (byte)((address >> 8) & 0xFF),
  251. (byte)((address >> 16) & 0xFF),
  252. (byte)(address >> 24) };
  253. }
  254. }
  255. #endif
  256. public AddressFamily AddressFamily
  257. {
  258. get {
  259. return _family;
  260. }
  261. }
  262. /// <summary>
  263. /// Used to tell whether an address is a loopback.
  264. /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
  265. /// the range 0-255, are loopback addresses.
  266. /// </summary>
  267. /// <param name="addr">Address to compare</param>
  268. /// <returns></returns>
  269. public static bool IsLoopback (IPAddress addr)
  270. {
  271. if(addr._family == AddressFamily.InterNetwork)
  272. return (addr.address & 0xFF) == 127;
  273. else {
  274. for(int i=0; i<6; i++) {
  275. if(addr._numbers[i] != 0)
  276. return false;
  277. }
  278. return NetworkToHostOrder((short)addr._numbers[7]) == 1;
  279. }
  280. }
  281. /// <summary>
  282. /// Overrides System.Object.ToString to return
  283. /// this object rendered in a quad-dotted notation
  284. /// </summary>
  285. public override string ToString ()
  286. {
  287. if(_family == AddressFamily.InterNetwork)
  288. return ToString (address);
  289. else
  290. {
  291. ushort[] numbers = _numbers.Clone() as ushort[];
  292. for(int i=0; i<numbers.Length; i++)
  293. numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
  294. return new IPv6Address(numbers).ToString();
  295. }
  296. }
  297. /// <summary>
  298. /// Returns this object rendered in a quad-dotted notation
  299. /// </summary>
  300. static string ToString (long addr)
  301. {
  302. // addr is in network order
  303. return (addr & 0xff).ToString () + "." +
  304. ((addr >> 8) & 0xff).ToString () + "." +
  305. ((addr >> 16) & 0xff).ToString () + "." +
  306. ((addr >> 24) & 0xff).ToString ();
  307. }
  308. /// <returns>
  309. /// Whether both objects are equal.
  310. /// </returns>
  311. public override bool Equals (object other)
  312. {
  313. if (other is System.Net.IPAddress){
  314. IPAddress otherAddr = other as IPAddress;
  315. if(AddressFamily != otherAddr.AddressFamily)
  316. return false;
  317. if(AddressFamily == AddressFamily.InterNetwork) {
  318. return address == otherAddr.address;
  319. } else {
  320. ushort[] vals = otherAddr._numbers;
  321. for(int i=0; i<8; i++)
  322. if(_numbers[i] != vals[i])
  323. return false;
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. public override int GetHashCode ()
  330. {
  331. if(_family == AddressFamily.InterNetwork)
  332. return (int)address;
  333. else
  334. return Hash (((((int) _numbers[0]) << 16) + _numbers [1]),
  335. ((((int) _numbers [2]) << 16) + _numbers [3]),
  336. ((((int) _numbers [4]) << 16) + _numbers [5]),
  337. ((((int) _numbers [6]) << 16) + _numbers [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. }