IPAddress.cs 11 KB

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