PageRenderTime 92ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/mcs/class/System/System.Net/IPAddress.cs

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