IPAddress.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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 m_Address;
  44. private AddressFamily m_Family = AddressFamily.InterNetwork;
  45. private ushort[] m_Numbers = new ushort[8]; /// ip6 Stored in network order (as ip4)
  46. private long m_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. public static readonly IPAddress IPv6Any = IPAddress.ParseIPV6 ("::");
  52. public static readonly IPAddress IPv6Loopback = IPAddress.ParseIPV6 ("::1");
  53. public static readonly IPAddress IPv6None = IPAddress.ParseIPV6 ("::");
  54. private static short SwapShort (short number)
  55. {
  56. return (short) ( ((number >> 8) & 0xFF) | ((number << 8) & 0xFF00) );
  57. }
  58. private static int SwapInt (int number)
  59. {
  60. return (((number >> 24) & 0xFF)
  61. | ((number >> 08) & 0xFF00)
  62. | ((number << 08) & 0xFF0000)
  63. | ((number << 24)));
  64. }
  65. private static long SwapLong(long number)
  66. {
  67. return (((number >> 56) & 0xFF)
  68. | ((number >> 40) & 0xFF00)
  69. | ((number >> 24) & 0xFF0000)
  70. | ((number >> 08) & 0xFF000000)
  71. | ((number << 08) & 0xFF00000000)
  72. | ((number << 24) & 0xFF0000000000)
  73. | ((number << 40) & 0xFF000000000000)
  74. | ((number << 56)));
  75. }
  76. public static short HostToNetworkOrder(short host) {
  77. if (!BitConverter.IsLittleEndian)
  78. return(host);
  79. return SwapShort (host);
  80. }
  81. public static int HostToNetworkOrder(int host) {
  82. if (!BitConverter.IsLittleEndian)
  83. return(host);
  84. return SwapInt (host);
  85. }
  86. public static long HostToNetworkOrder(long host) {
  87. if (!BitConverter.IsLittleEndian)
  88. return(host);
  89. return SwapLong (host);
  90. }
  91. public static short NetworkToHostOrder(short network) {
  92. if (!BitConverter.IsLittleEndian)
  93. return(network);
  94. return SwapShort (network);
  95. }
  96. public static int NetworkToHostOrder(int network) {
  97. if (!BitConverter.IsLittleEndian)
  98. return(network);
  99. return SwapInt (network);
  100. }
  101. public static long NetworkToHostOrder(long network) {
  102. if (!BitConverter.IsLittleEndian)
  103. return(network);
  104. return SwapLong (network);
  105. }
  106. /// <summary>
  107. /// Constructor from a 32-bit constant with the address bytes in
  108. /// little-endian order (the lower order bytes contain the netid)
  109. /// </summary>
  110. public IPAddress (long addr)
  111. {
  112. m_Address = addr;
  113. }
  114. public IPAddress (byte[] address)
  115. {
  116. if (address == null)
  117. throw new ArgumentNullException ("address");
  118. int len = address.Length;
  119. #if NET_2_0
  120. if (len != 16 && len != 4)
  121. throw new ArgumentException ("An invalid IP address was specified.",
  122. "address");
  123. #else
  124. if (len != 16)
  125. throw new ArgumentException ("address");
  126. #endif
  127. if (len == 16) {
  128. Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
  129. m_Family = AddressFamily.InterNetworkV6;
  130. m_ScopeId = 0;
  131. } else {
  132. m_Address = (address [3] << 24) + (address [2] << 16) +
  133. (address [1] << 8) + address [0];
  134. }
  135. }
  136. public IPAddress(byte[] address, long scopeId)
  137. {
  138. if (address == null)
  139. throw new ArgumentNullException ("address");
  140. if (address.Length != 16)
  141. #if NET_2_0
  142. throw new ArgumentException ("An invalid IP address was specified.",
  143. "address");
  144. #else
  145. throw new ArgumentException("address");
  146. #endif
  147. Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
  148. m_Family = AddressFamily.InterNetworkV6;
  149. m_ScopeId = scopeId;
  150. }
  151. internal IPAddress(ushort[] address, long scopeId)
  152. {
  153. m_Numbers = address;
  154. for(int i=0; i<8; i++)
  155. m_Numbers[i] = (ushort)HostToNetworkOrder((short)m_Numbers[i]);
  156. m_Family = AddressFamily.InterNetworkV6;
  157. m_ScopeId = scopeId;
  158. }
  159. public static IPAddress Parse (string ip)
  160. {
  161. IPAddress ret;
  162. if (TryParse (ip, out ret))
  163. return ret;
  164. throw new FormatException("An invalid IP address was specified.");
  165. }
  166. #if NET_2_0
  167. public
  168. #endif
  169. static bool TryParse (string ip, out IPAddress address)
  170. {
  171. if (ip == null)
  172. throw new ArgumentNullException ("Value cannot be null.");
  173. if( (address = ParseIPV4(ip)) == null)
  174. if( (address = ParseIPV6(ip)) == null)
  175. return false;
  176. return true;
  177. }
  178. private static IPAddress ParseIPV4 (string ip)
  179. {
  180. if (ip.Length == 0 || ip == " ")
  181. return new IPAddress (0);
  182. int pos = ip.IndexOf (' ');
  183. if (pos != -1)
  184. ip = ip.Substring (0, pos);
  185. if (ip.Length == 0 || ip [ip.Length - 1] == '.')
  186. return null;
  187. string [] ips = ip.Split (new char [] {'.'});
  188. if (ips.Length > 4)
  189. return null;
  190. // Make the number in network order
  191. try
  192. {
  193. long a = 0;
  194. byte val = 0;
  195. for (int i = 0; i < ips.Length; i++) {
  196. string subnet = ips [i];
  197. if ((3 <= subnet.Length && subnet.Length <= 4) &&
  198. (subnet [0] == '0') &&
  199. (subnet [1] == 'x' || subnet [2] == 'X')) {
  200. if (subnet.Length == 3)
  201. val = (byte) Uri.FromHex (subnet [2]);
  202. else
  203. val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
  204. } else if (subnet.Length == 0)
  205. return null;
  206. else
  207. val = Byte.Parse (subnet, NumberStyles.None);
  208. if (ips.Length < 4 && i == (ips.Length - 1))
  209. i = 3;
  210. a |= (long) val << (i << 3);
  211. }
  212. return (new IPAddress (a));
  213. } catch (Exception) {
  214. return null;
  215. }
  216. }
  217. private static IPAddress ParseIPV6 (string ip)
  218. {
  219. try
  220. {
  221. IPv6Address newIPv6Address = IPv6Address.Parse(ip);
  222. return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);
  223. }
  224. catch (Exception) {
  225. return null;
  226. }
  227. }
  228. [Obsolete("This property is obsolete. Use GetAddressBytes.")]
  229. public long Address
  230. {
  231. get {
  232. if(m_Family != AddressFamily.InterNetwork)
  233. throw new Exception("The attempted operation is not supported for the type of object referenced");
  234. return m_Address;
  235. }
  236. set {
  237. /* no need to do this test, ms.net accepts any value.
  238. if (value < 0 || value > 0x00000000FFFFFFFF)
  239. throw new ArgumentOutOfRangeException (
  240. "the address must be between 0 and 0xFFFFFFFF");
  241. */
  242. if(m_Family != AddressFamily.InterNetwork)
  243. throw new Exception("The attempted operation is not supported for the type of object referenced");
  244. m_Address = value;
  245. }
  246. }
  247. internal long InternalIPv4Address {
  248. get { return m_Address; }
  249. }
  250. #if NET_2_0
  251. public bool IsIPv6LinkLocal {
  252. get {
  253. if (m_Family == AddressFamily.InterNetwork)
  254. return false;
  255. int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
  256. return 0xFE80 <= v && v < 0xFEC0;
  257. }
  258. }
  259. public bool IsIPv6SiteLocal {
  260. get {
  261. if (m_Family == AddressFamily.InterNetwork)
  262. return false;
  263. int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
  264. return 0xFEC0 <= v && v < 0xFF00;
  265. }
  266. }
  267. public bool IsIPv6Multicast {
  268. get {
  269. return m_Family != AddressFamily.InterNetwork &&
  270. ((ushort) NetworkToHostOrder ((short) m_Numbers [0]) & 0xFF00) == 0xFF00;
  271. }
  272. }
  273. #endif
  274. public long ScopeId {
  275. get {
  276. if(m_Family != AddressFamily.InterNetworkV6)
  277. throw new Exception("The attempted operation is not supported for the type of object referenced");
  278. return m_ScopeId;
  279. }
  280. set {
  281. if(m_Family != AddressFamily.InterNetworkV6)
  282. throw new Exception("The attempted operation is not supported for the type of object referenced");
  283. m_ScopeId = value;
  284. }
  285. }
  286. public byte [] GetAddressBytes ()
  287. {
  288. if(m_Family == AddressFamily.InterNetworkV6) {
  289. byte [] addressBytes = new byte [16];
  290. Buffer.BlockCopy (m_Numbers, 0, addressBytes, 0, 16);
  291. return addressBytes;
  292. } else {
  293. return new byte [4] { (byte)(m_Address & 0xFF),
  294. (byte)((m_Address >> 8) & 0xFF),
  295. (byte)((m_Address >> 16) & 0xFF),
  296. (byte)(m_Address >> 24) };
  297. }
  298. }
  299. public AddressFamily AddressFamily
  300. {
  301. get {
  302. return m_Family;
  303. }
  304. }
  305. /// <summary>
  306. /// Used to tell whether an address is a loopback.
  307. /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
  308. /// the range 0-255, are loopback addresses.
  309. /// </summary>
  310. /// <param name="addr">Address to compare</param>
  311. /// <returns></returns>
  312. public static bool IsLoopback (IPAddress addr)
  313. {
  314. if(addr.m_Family == AddressFamily.InterNetwork)
  315. return (addr.m_Address & 0xFF) == 127;
  316. else {
  317. for(int i=0; i<6; i++) {
  318. if(addr.m_Numbers[i] != 0)
  319. return false;
  320. }
  321. return NetworkToHostOrder((short)addr.m_Numbers[7]) == 1;
  322. }
  323. }
  324. /// <summary>
  325. /// Overrides System.Object.ToString to return
  326. /// this object rendered in a quad-dotted notation
  327. /// </summary>
  328. public override string ToString ()
  329. {
  330. if(m_Family == AddressFamily.InterNetwork)
  331. return ToString (m_Address);
  332. else
  333. {
  334. ushort[] numbers = m_Numbers.Clone() as ushort[];
  335. for(int i=0; i<numbers.Length; i++)
  336. numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
  337. IPv6Address v6 = new IPv6Address(numbers);
  338. v6.ScopeId = ScopeId;
  339. return v6.ToString();
  340. }
  341. }
  342. /// <summary>
  343. /// Returns this object rendered in a quad-dotted notation
  344. /// </summary>
  345. static string ToString (long addr)
  346. {
  347. // addr is in network order
  348. return (addr & 0xff).ToString () + "." +
  349. ((addr >> 8) & 0xff).ToString () + "." +
  350. ((addr >> 16) & 0xff).ToString () + "." +
  351. ((addr >> 24) & 0xff).ToString ();
  352. }
  353. /// <returns>
  354. /// Whether both objects are equal.
  355. /// </returns>
  356. public override bool Equals (object other)
  357. {
  358. if (other is System.Net.IPAddress){
  359. IPAddress otherAddr = other as IPAddress;
  360. if(AddressFamily != otherAddr.AddressFamily)
  361. return false;
  362. if(AddressFamily == AddressFamily.InterNetwork) {
  363. return m_Address == otherAddr.m_Address;
  364. } else {
  365. ushort[] vals = otherAddr.m_Numbers;
  366. for(int i=0; i<8; i++)
  367. if(m_Numbers[i] != vals[i])
  368. return false;
  369. return true;
  370. }
  371. }
  372. return false;
  373. }
  374. public override int GetHashCode ()
  375. {
  376. if(m_Family == AddressFamily.InterNetwork)
  377. return (int)m_Address;
  378. else
  379. return Hash (((((int) m_Numbers[0]) << 16) + m_Numbers [1]),
  380. ((((int) m_Numbers [2]) << 16) + m_Numbers [3]),
  381. ((((int) m_Numbers [4]) << 16) + m_Numbers [5]),
  382. ((((int) m_Numbers [6]) << 16) + m_Numbers [7]));
  383. }
  384. private static int Hash (int i, int j, int k, int l)
  385. {
  386. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  387. }
  388. #pragma warning disable 169
  389. // Added for serialization compatibility with MS.NET
  390. private int m_HashCode;
  391. #pragma warning restore
  392. }
  393. }