IPAddress.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 ipString)
  160. {
  161. IPAddress ret;
  162. if (TryParse (ipString, 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 ipString, out IPAddress address)
  170. {
  171. if (ipString == null)
  172. throw new ArgumentNullException ("ipString");
  173. if ((address = ParseIPV4 (ipString)) == null)
  174. if ((address = ParseIPV6 (ipString)) == null)
  175. return false;
  176. return true;
  177. }
  178. private static IPAddress ParseIPV4 (string ip)
  179. {
  180. #if ONLY_1_1
  181. if (ip.Length == 0 || ip == " ")
  182. return new IPAddress (0);
  183. #endif
  184. int pos = ip.IndexOf (' ');
  185. if (pos != -1) {
  186. #if NET_2_0
  187. string [] nets = ip.Substring (pos + 1).Split (new char [] {'.'});
  188. if (nets.Length > 0) {
  189. string lastNet = nets [nets.Length - 1];
  190. if (lastNet.Length == 0)
  191. return null;
  192. #if NET_2_1
  193. foreach (char c in lastNet.ToCharArray ())
  194. #else
  195. foreach (char c in lastNet)
  196. #endif
  197. if (!Uri.IsHexDigit (c))
  198. return null;
  199. }
  200. #endif
  201. ip = ip.Substring (0, pos);
  202. }
  203. if (ip.Length == 0 || ip [ip.Length - 1] == '.')
  204. return null;
  205. string [] ips = ip.Split (new char [] {'.'});
  206. if (ips.Length > 4)
  207. return null;
  208. // Make the number in network order
  209. try {
  210. long a = 0;
  211. byte val = 0;
  212. for (int i = 0; i < ips.Length; i++) {
  213. string subnet = ips [i];
  214. if ((3 <= subnet.Length && subnet.Length <= 4) &&
  215. (subnet [0] == '0') &&
  216. (subnet [1] == 'x' || subnet [2] == 'X')) {
  217. if (subnet.Length == 3)
  218. val = (byte) Uri.FromHex (subnet [2]);
  219. else
  220. val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
  221. } else if (subnet.Length == 0)
  222. return null;
  223. else
  224. val = byte.Parse (subnet, NumberStyles.None);
  225. if (ips.Length < 4 && i == (ips.Length - 1))
  226. i = 3;
  227. a |= (long) val << (i << 3);
  228. }
  229. return (new IPAddress (a));
  230. } catch (Exception) {
  231. return null;
  232. }
  233. }
  234. private static IPAddress ParseIPV6 (string ip)
  235. {
  236. try {
  237. IPv6Address newIPv6Address = IPv6Address.Parse(ip);
  238. return new IPAddress (newIPv6Address.Address, newIPv6Address.ScopeId);
  239. } catch (Exception) {
  240. return null;
  241. }
  242. }
  243. [Obsolete("This property is obsolete. Use GetAddressBytes.")]
  244. public long Address
  245. {
  246. get {
  247. if(m_Family != AddressFamily.InterNetwork)
  248. throw new Exception("The attempted operation is not supported for the type of object referenced");
  249. return m_Address;
  250. }
  251. set {
  252. /* no need to do this test, ms.net accepts any value.
  253. if (value < 0 || value > 0x00000000FFFFFFFF)
  254. throw new ArgumentOutOfRangeException (
  255. "the address must be between 0 and 0xFFFFFFFF");
  256. */
  257. if(m_Family != AddressFamily.InterNetwork)
  258. throw new Exception("The attempted operation is not supported for the type of object referenced");
  259. m_Address = value;
  260. }
  261. }
  262. internal long InternalIPv4Address {
  263. get { return m_Address; }
  264. }
  265. #if NET_2_0
  266. public bool IsIPv6LinkLocal {
  267. get {
  268. if (m_Family == AddressFamily.InterNetwork)
  269. return false;
  270. int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
  271. return 0xFE80 <= v && v < 0xFEC0;
  272. }
  273. }
  274. public bool IsIPv6SiteLocal {
  275. get {
  276. if (m_Family == AddressFamily.InterNetwork)
  277. return false;
  278. int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
  279. return 0xFEC0 <= v && v < 0xFF00;
  280. }
  281. }
  282. public bool IsIPv6Multicast {
  283. get {
  284. return m_Family != AddressFamily.InterNetwork &&
  285. ((ushort) NetworkToHostOrder ((short) m_Numbers [0]) & 0xFF00) == 0xFF00;
  286. }
  287. }
  288. #endif
  289. public long ScopeId {
  290. get {
  291. if(m_Family != AddressFamily.InterNetworkV6)
  292. throw new Exception("The attempted operation is not supported for the type of object referenced");
  293. return m_ScopeId;
  294. }
  295. set {
  296. if(m_Family != AddressFamily.InterNetworkV6)
  297. throw new Exception("The attempted operation is not supported for the type of object referenced");
  298. m_ScopeId = value;
  299. }
  300. }
  301. public byte [] GetAddressBytes ()
  302. {
  303. if(m_Family == AddressFamily.InterNetworkV6) {
  304. byte [] addressBytes = new byte [16];
  305. Buffer.BlockCopy (m_Numbers, 0, addressBytes, 0, 16);
  306. return addressBytes;
  307. } else {
  308. return new byte [4] { (byte)(m_Address & 0xFF),
  309. (byte)((m_Address >> 8) & 0xFF),
  310. (byte)((m_Address >> 16) & 0xFF),
  311. (byte)(m_Address >> 24) };
  312. }
  313. }
  314. public AddressFamily AddressFamily
  315. {
  316. get {
  317. return m_Family;
  318. }
  319. }
  320. /// <summary>
  321. /// Used to tell whether an address is a loopback.
  322. /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
  323. /// the range 0-255, are loopback addresses.
  324. /// </summary>
  325. /// <param name="addr">Address to compare</param>
  326. /// <returns></returns>
  327. public static bool IsLoopback (IPAddress addr)
  328. {
  329. if(addr.m_Family == AddressFamily.InterNetwork)
  330. return (addr.m_Address & 0xFF) == 127;
  331. else {
  332. for(int i=0; i<6; i++) {
  333. if(addr.m_Numbers[i] != 0)
  334. return false;
  335. }
  336. return NetworkToHostOrder((short)addr.m_Numbers[7]) == 1;
  337. }
  338. }
  339. /// <summary>
  340. /// Overrides System.Object.ToString to return
  341. /// this object rendered in a quad-dotted notation
  342. /// </summary>
  343. public override string ToString ()
  344. {
  345. if(m_Family == AddressFamily.InterNetwork)
  346. return ToString (m_Address);
  347. else
  348. {
  349. ushort[] numbers = m_Numbers.Clone() as ushort[];
  350. for(int i=0; i<numbers.Length; i++)
  351. numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
  352. IPv6Address v6 = new IPv6Address(numbers);
  353. v6.ScopeId = ScopeId;
  354. return v6.ToString();
  355. }
  356. }
  357. /// <summary>
  358. /// Returns this object rendered in a quad-dotted notation
  359. /// </summary>
  360. static string ToString (long addr)
  361. {
  362. // addr is in network order
  363. return (addr & 0xff).ToString () + "." +
  364. ((addr >> 8) & 0xff).ToString () + "." +
  365. ((addr >> 16) & 0xff).ToString () + "." +
  366. ((addr >> 24) & 0xff).ToString ();
  367. }
  368. /// <returns>
  369. /// Whether both objects are equal.
  370. /// </returns>
  371. public override bool Equals (object other)
  372. {
  373. if (other is System.Net.IPAddress){
  374. IPAddress otherAddr = other as IPAddress;
  375. if(AddressFamily != otherAddr.AddressFamily)
  376. return false;
  377. if(AddressFamily == AddressFamily.InterNetwork) {
  378. return m_Address == otherAddr.m_Address;
  379. } else {
  380. ushort[] vals = otherAddr.m_Numbers;
  381. for(int i=0; i<8; i++)
  382. if(m_Numbers[i] != vals[i])
  383. return false;
  384. return true;
  385. }
  386. }
  387. return false;
  388. }
  389. public override int GetHashCode ()
  390. {
  391. if(m_Family == AddressFamily.InterNetwork)
  392. return (int)m_Address;
  393. else
  394. return Hash (((((int) m_Numbers[0]) << 16) + m_Numbers [1]),
  395. ((((int) m_Numbers [2]) << 16) + m_Numbers [3]),
  396. ((((int) m_Numbers [4]) << 16) + m_Numbers [5]),
  397. ((((int) m_Numbers [6]) << 16) + m_Numbers [7]));
  398. }
  399. private static int Hash (int i, int j, int k, int l)
  400. {
  401. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  402. }
  403. #pragma warning disable 169
  404. // Added for serialization compatibility with MS.NET
  405. private int m_HashCode;
  406. #pragma warning restore
  407. }
  408. }