IPAddress.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  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. #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. m_Address = addr;
  117. }
  118. #if NET_1_1
  119. public IPAddress (byte[] address)
  120. {
  121. int len = address.Length;
  122. #if NET_2_0
  123. if (len != 16 && len != 4)
  124. throw new ArgumentException ("address");
  125. #else
  126. if (len != 16)
  127. throw new ArgumentException ("address");
  128. #endif
  129. if (len == 16) {
  130. Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
  131. m_Family = AddressFamily.InterNetworkV6;
  132. m_ScopeId = 0;
  133. } else {
  134. m_Address = (address [3] << 24) + (address [2] << 16) +
  135. (address [1] << 8) + address [0];
  136. }
  137. }
  138. public IPAddress(byte[] address, long scopeId)
  139. {
  140. if (address.Length != 16)
  141. throw new ArgumentException("address");
  142. Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
  143. m_Family = AddressFamily.InterNetworkV6;
  144. m_ScopeId = scopeId;
  145. }
  146. internal IPAddress(ushort[] address, long scopeId)
  147. {
  148. m_Numbers = address;
  149. for(int i=0; i<8; i++)
  150. m_Numbers[i] = (ushort)HostToNetworkOrder((short)m_Numbers[i]);
  151. m_Family = AddressFamily.InterNetworkV6;
  152. m_ScopeId = scopeId;
  153. }
  154. #endif
  155. public static IPAddress Parse (string ip)
  156. {
  157. IPAddress ret;
  158. if (ip == null)
  159. throw new ArgumentNullException ("Value cannot be null.");
  160. #if NET_1_1
  161. if( (ret = ParseIPV4(ip)) == null)
  162. if( (ret = ParseIPV6(ip)) == null)
  163. throw new FormatException("An invalid IP address was specified.");
  164. #else
  165. if( (ret = ParseIPV4(ip)) == null)
  166. throw new FormatException("An invalid IP address was specified.");
  167. #endif
  168. return ret;
  169. }
  170. private static IPAddress ParseIPV4 (string ip)
  171. {
  172. if (ip.Length == 0 || ip == " ")
  173. return new IPAddress (0);
  174. int pos = ip.IndexOf (' ');
  175. if (pos != -1)
  176. ip = ip.Substring (0, pos);
  177. if (ip.Length == 0 || ip [ip.Length - 1] == '.')
  178. return null;
  179. string [] ips = ip.Split (new char [] {'.'});
  180. if (ips.Length > 4)
  181. return null;
  182. // Make the number in network order
  183. try
  184. {
  185. long a = 0;
  186. byte val = 0;
  187. for (int i = 0; i < ips.Length; i++) {
  188. string subnet = ips [i];
  189. if ((3 <= subnet.Length && subnet.Length <= 4) &&
  190. (subnet [0] == '0') &&
  191. (subnet [1] == 'x' || subnet [2] == 'X')) {
  192. if (subnet.Length == 3)
  193. val = (byte) Uri.FromHex (subnet [2]);
  194. else
  195. val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
  196. } else if (subnet.Length == 0)
  197. return null;
  198. else
  199. val = Byte.Parse (subnet, NumberStyles.None);
  200. if (ips.Length < 4 && i == (ips.Length - 1))
  201. i = 3;
  202. a |= (long) val << (i << 3);
  203. }
  204. return (new IPAddress (a));
  205. } catch (Exception) {
  206. return null;
  207. }
  208. }
  209. #if NET_1_1
  210. private static IPAddress ParseIPV6 (string ip)
  211. {
  212. try
  213. {
  214. IPv6Address newIPv6Address = IPv6Address.Parse(ip);
  215. return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);
  216. }
  217. catch (Exception) {
  218. return null;
  219. }
  220. }
  221. [Obsolete("This property is obsolete. Use GetAddressBytes.")]
  222. #endif
  223. public long Address
  224. {
  225. get {
  226. if(m_Family != AddressFamily.InterNetwork)
  227. throw new Exception("The attempted operation is not supported for the type of object referenced");
  228. return m_Address;
  229. }
  230. set {
  231. /* no need to do this test, ms.net accepts any value.
  232. if (value < 0 || value > 0x00000000FFFFFFFF)
  233. throw new ArgumentOutOfRangeException (
  234. "the address must be between 0 and 0xFFFFFFFF");
  235. */
  236. if(m_Family != AddressFamily.InterNetwork)
  237. throw new Exception("The attempted operation is not supported for the type of object referenced");
  238. m_Address = value;
  239. }
  240. }
  241. internal long InternalIPv4Address {
  242. get { return m_Address; }
  243. }
  244. #if NET_1_1
  245. public long ScopeId {
  246. get {
  247. if(m_Family != AddressFamily.InterNetworkV6)
  248. throw new Exception("The attempted operation is not supported for the type of object referenced");
  249. return m_ScopeId;
  250. }
  251. set {
  252. if(m_Family != AddressFamily.InterNetworkV6)
  253. throw new Exception("The attempted operation is not supported for the type of object referenced");
  254. m_ScopeId = value;
  255. }
  256. }
  257. public byte [] GetAddressBytes ()
  258. {
  259. if(m_Family == AddressFamily.InterNetworkV6) {
  260. byte [] addressBytes = new byte [16];
  261. Buffer.BlockCopy (m_Numbers, 0, addressBytes, 0, 16);
  262. return addressBytes;
  263. } else {
  264. return new byte [4] { (byte)(m_Address & 0xFF),
  265. (byte)((m_Address >> 8) & 0xFF),
  266. (byte)((m_Address >> 16) & 0xFF),
  267. (byte)(m_Address >> 24) };
  268. }
  269. }
  270. #endif
  271. public AddressFamily AddressFamily
  272. {
  273. get {
  274. return m_Family;
  275. }
  276. }
  277. /// <summary>
  278. /// Used to tell whether an address is a loopback.
  279. /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
  280. /// the range 0-255, are loopback addresses.
  281. /// </summary>
  282. /// <param name="addr">Address to compare</param>
  283. /// <returns></returns>
  284. public static bool IsLoopback (IPAddress addr)
  285. {
  286. if(addr.m_Family == AddressFamily.InterNetwork)
  287. return (addr.m_Address & 0xFF) == 127;
  288. else {
  289. for(int i=0; i<6; i++) {
  290. if(addr.m_Numbers[i] != 0)
  291. return false;
  292. }
  293. return NetworkToHostOrder((short)addr.m_Numbers[7]) == 1;
  294. }
  295. }
  296. /// <summary>
  297. /// Overrides System.Object.ToString to return
  298. /// this object rendered in a quad-dotted notation
  299. /// </summary>
  300. public override string ToString ()
  301. {
  302. if(m_Family == AddressFamily.InterNetwork)
  303. return ToString (m_Address);
  304. else
  305. {
  306. ushort[] numbers = m_Numbers.Clone() as ushort[];
  307. for(int i=0; i<numbers.Length; i++)
  308. numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
  309. return new IPv6Address(numbers).ToString();
  310. }
  311. }
  312. /// <summary>
  313. /// Returns this object rendered in a quad-dotted notation
  314. /// </summary>
  315. static string ToString (long addr)
  316. {
  317. // addr is in network order
  318. return (addr & 0xff).ToString () + "." +
  319. ((addr >> 8) & 0xff).ToString () + "." +
  320. ((addr >> 16) & 0xff).ToString () + "." +
  321. ((addr >> 24) & 0xff).ToString ();
  322. }
  323. /// <returns>
  324. /// Whether both objects are equal.
  325. /// </returns>
  326. public override bool Equals (object other)
  327. {
  328. if (other is System.Net.IPAddress){
  329. IPAddress otherAddr = other as IPAddress;
  330. if(AddressFamily != otherAddr.AddressFamily)
  331. return false;
  332. if(AddressFamily == AddressFamily.InterNetwork) {
  333. return m_Address == otherAddr.m_Address;
  334. } else {
  335. ushort[] vals = otherAddr.m_Numbers;
  336. for(int i=0; i<8; i++)
  337. if(m_Numbers[i] != vals[i])
  338. return false;
  339. return true;
  340. }
  341. }
  342. return false;
  343. }
  344. public override int GetHashCode ()
  345. {
  346. if(m_Family == AddressFamily.InterNetwork)
  347. return (int)m_Address;
  348. else
  349. return Hash (((((int) m_Numbers[0]) << 16) + m_Numbers [1]),
  350. ((((int) m_Numbers [2]) << 16) + m_Numbers [3]),
  351. ((((int) m_Numbers [4]) << 16) + m_Numbers [5]),
  352. ((((int) m_Numbers [6]) << 16) + m_Numbers [7]));
  353. }
  354. private static int Hash (int i, int j, int k, int l)
  355. {
  356. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  357. }
  358. #pragma warning disable 169
  359. // Added for serialization compatibility with MS.NET
  360. private int m_HashCode;
  361. #pragma warning restore
  362. }
  363. }