IPAddress.cs 13 KB

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