IPAddress.cs 14 KB

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