IPAddress.cs 11 KB

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