IPAddress.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. //
  11. // Note: the address is stored in host order
  12. using System;
  13. using System.Globalization;
  14. using System.Net.Sockets;
  15. using System.Runtime.InteropServices;
  16. namespace System.Net {
  17. /// <remarks>
  18. /// Encapsulates an IP Address.
  19. /// </remarks>
  20. [Serializable]
  21. public class IPAddress {
  22. // Don't change the name of this field without also
  23. // changing socket-io.c in the runtime
  24. private long address;
  25. private AddressFamily _family = AddressFamily.InterNetwork;
  26. private ushort[] _numbers = new ushort[8]; /// ip6 Stored in network order (as ip4)
  27. private long _scopeId = 0;
  28. public static readonly IPAddress Any = new IPAddress(0);
  29. public static readonly IPAddress Broadcast = IPAddress.Parse ("255.255.255.255");
  30. public static readonly IPAddress Loopback = IPAddress.Parse ("127.0.0.1");
  31. public static readonly IPAddress None = IPAddress.Parse ("255.255.255.255");
  32. #if NET_1_1
  33. public static readonly IPAddress IPv6Any = IPAddress.Parse ("::");
  34. public static readonly IPAddress IPv6Loopback = IPAddress.Parse ("::1");
  35. public static readonly IPAddress IPv6None = IPAddress.Parse ("::");
  36. #endif
  37. private static short SwapShort (short number)
  38. {
  39. return (short) ( ((number >> 8) & 0xFF) + ((number << 8) & 0xFF00) );
  40. }
  41. private static int SwapInt (int number)
  42. {
  43. byte b0 = (byte) ((number >> 24) & 0xFF);
  44. byte b1 = (byte) ((number >> 16) & 0xFF);
  45. byte b2 = (byte) ((number >> 8) & 0xFF);
  46. byte b3 = (byte) (number & 0xFF);
  47. return b0 + (b1 << 8) + (b2 << 16) + (b3 << 24);
  48. }
  49. private static long SwapLong (long number)
  50. {
  51. byte b0 = (byte) ((number >> 56) & 0xFF);
  52. byte b1 = (byte) ((number >> 48) & 0xFF);
  53. byte b2 = (byte) ((number >> 40) & 0xFF);
  54. byte b3 = (byte) ((number >> 32) & 0xFF);
  55. byte b4 = (byte) ((number >> 24) & 0xFF);
  56. byte b5 = (byte) ((number >> 16) & 0xFF);
  57. byte b6 = (byte) ((number >> 8) & 0xFF);
  58. byte b7 = (byte) (number & 0xFF);
  59. return (long) b0 + ((long) b1 << 8) + ((long) b2 << 16) + ((long) b3 << 24) + ((long) b4 << 32) + ((long) b5 << 40) + ((long) b6 << 48) + ((long) b7 << 56);
  60. }
  61. public static short HostToNetworkOrder(short host) {
  62. if (!BitConverter.IsLittleEndian)
  63. return(host);
  64. return SwapShort (host);
  65. }
  66. public static int HostToNetworkOrder(int host) {
  67. if (!BitConverter.IsLittleEndian)
  68. return(host);
  69. return SwapInt (host);
  70. }
  71. public static long HostToNetworkOrder(long host) {
  72. if (!BitConverter.IsLittleEndian)
  73. return(host);
  74. return SwapLong (host);
  75. }
  76. public static short NetworkToHostOrder(short network) {
  77. if (!BitConverter.IsLittleEndian)
  78. return(network);
  79. return SwapShort (network);
  80. }
  81. public static int NetworkToHostOrder(int network) {
  82. if (!BitConverter.IsLittleEndian)
  83. return(network);
  84. return SwapInt (network);
  85. }
  86. public static long NetworkToHostOrder(long network) {
  87. if (!BitConverter.IsLittleEndian)
  88. return(network);
  89. return SwapLong (network);
  90. }
  91. /// <summary>
  92. /// Constructor from a 32-bit constant with its bytes
  93. /// in network order.
  94. /// </summary>
  95. public IPAddress (long addr)
  96. {
  97. address = addr;
  98. }
  99. #if NET_1_1
  100. public IPAddress(byte[] address) : this(address, 0)
  101. {
  102. }
  103. public IPAddress(byte[] address, long scopeId)
  104. {
  105. if(address.Length != 16)
  106. throw new ArgumentException("address");
  107. Buffer.BlockCopy(address, 0, _numbers, 0, 16);
  108. _family = AddressFamily.InterNetworkV6;
  109. _scopeId = scopeId;
  110. }
  111. internal IPAddress(ushort[] address, long scopeId)
  112. {
  113. _numbers = address;
  114. for(int i=0; i<8; i++)
  115. _numbers[i] = (ushort)HostToNetworkOrder((short)_numbers[i]);
  116. _family = AddressFamily.InterNetworkV6;
  117. _scopeId = scopeId;
  118. }
  119. #endif
  120. public static IPAddress Parse (string ip)
  121. {
  122. IPAddress ret;
  123. if (ip == null)
  124. throw new ArgumentNullException ("Value cannot be null.");
  125. #if NET_1_1
  126. if( (ret = ParseIPV4(ip)) == null)
  127. if( (ret = ParseIPV6(ip)) == null)
  128. throw new FormatException("An invalid IP address was specified.");
  129. #else
  130. if( (ret = ParseIPV4(ip)) == null)
  131. throw new FormatException("An invalid IP address was specified.");
  132. #endif
  133. return ret;
  134. }
  135. private static IPAddress ParseIPV4 (string ip)
  136. {
  137. if (ip.Length == 0 || ip [0] == ' ')
  138. return new IPAddress (0);
  139. int pos = ip.IndexOf (' ');
  140. if (pos != -1)
  141. ip = ip.Substring (0, pos);
  142. else if (ip [ip.Length - 1] == '.')
  143. return null;
  144. string [] ips = ip.Split (new char [] {'.'});
  145. if (ips.Length > 4)
  146. return null;
  147. // Make the number in network order
  148. try
  149. {
  150. long a = 0;
  151. byte val = 0;
  152. for (int i = 0; i < ips.Length; i++) {
  153. string subnet = ips [i];
  154. if ((3 <= subnet.Length && subnet.Length <= 4) &&
  155. (subnet [0] == '0') &&
  156. (subnet [1] == 'x' || subnet [2] == 'X')) {
  157. if (subnet.Length == 3)
  158. val = (byte) Uri.FromHex (subnet [2]);
  159. else
  160. val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
  161. } else if (subnet.Length == 0)
  162. val = 0;
  163. else
  164. val = Byte.Parse (subnet, NumberStyles.None);
  165. if (ips.Length < 4 && i == (ips.Length - 1))
  166. i = 3;
  167. a |= (long) val << (i << 3);
  168. }
  169. return (new IPAddress (a));
  170. } catch (Exception) {
  171. return null;
  172. }
  173. }
  174. #if NET_1_1
  175. private static IPAddress ParseIPV6 (string ip)
  176. {
  177. try
  178. {
  179. IPv6Address newIPv6Address = IPv6Address.Parse(ip);
  180. return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);
  181. }
  182. catch (Exception) {
  183. return null;
  184. }
  185. }
  186. [Obsolete]
  187. #endif
  188. public long Address
  189. {
  190. get {
  191. if(_family != AddressFamily.InterNetwork)
  192. throw new Exception("The attempted operation is not supported for the type of object referenced");
  193. return address;
  194. }
  195. set {
  196. /* no need to do this test, ms.net accepts any value.
  197. if (value < 0 || value > 0x00000000FFFFFFFF)
  198. throw new ArgumentOutOfRangeException (
  199. "the address must be between 0 and 0xFFFFFFFF");
  200. */
  201. if(_family != AddressFamily.InterNetwork)
  202. throw new Exception("The attempted operation is not supported for the type of object referenced");
  203. address = value;
  204. }
  205. }
  206. #if NET_1_1
  207. public long ScopeId {
  208. get {
  209. if(_family != AddressFamily.InterNetworkV6)
  210. throw new Exception("The attempted operation is not supported for the type of object referenced");
  211. return _scopeId;
  212. }
  213. set {
  214. if(_family != AddressFamily.InterNetworkV6)
  215. throw new Exception("The attempted operation is not supported for the type of object referenced");
  216. _scopeId = value;
  217. }
  218. }
  219. public byte[] GetAddressBytes()
  220. {
  221. if(_family == AddressFamily.InterNetworkV6)
  222. {
  223. byte[] addressBytes = new byte[16];
  224. Buffer.BlockCopy(_numbers, 0, addressBytes, 0, 16);
  225. return addressBytes;
  226. }
  227. else
  228. {
  229. return new byte[4] { (byte)(address & 0xFF),
  230. (byte)((address >> 8) & 0xFF),
  231. (byte)((address >> 16) & 0xFF),
  232. (byte)(address >> 24) };
  233. }
  234. }
  235. #endif
  236. public AddressFamily AddressFamily
  237. {
  238. get {
  239. return _family;
  240. }
  241. }
  242. /// <summary>
  243. /// Used to tell whether an address is a loopback.
  244. /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
  245. /// the range 0-255, are loopback addresses.
  246. /// </summary>
  247. /// <param name="addr">Address to compare</param>
  248. /// <returns></returns>
  249. public static bool IsLoopback (IPAddress addr)
  250. {
  251. if(addr._family == AddressFamily.InterNetwork)
  252. return (addr.address & 0xFF) == 127;
  253. else {
  254. for(int i=0; i<6; i++) {
  255. if(addr._numbers[i] != 0)
  256. return false;
  257. }
  258. return NetworkToHostOrder((short)addr._numbers[7]) == 1;
  259. }
  260. }
  261. /// <summary>
  262. /// Overrides System.Object.ToString to return
  263. /// this object rendered in a quad-dotted notation
  264. /// </summary>
  265. public override string ToString ()
  266. {
  267. if(_family == AddressFamily.InterNetwork)
  268. return ToString (address);
  269. else
  270. {
  271. ushort[] numbers = _numbers.Clone() as ushort[];
  272. for(int i=0; i<numbers.Length; i++)
  273. numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
  274. return new IPv6Address(numbers).ToString();
  275. }
  276. }
  277. /// <summary>
  278. /// Returns this object rendered in a quad-dotted notation
  279. /// </summary>
  280. static string ToString (long addr)
  281. {
  282. // addr is in network order
  283. return (addr & 0xff).ToString () + "." +
  284. ((addr >> 8) & 0xff).ToString () + "." +
  285. ((addr >> 16) & 0xff).ToString () + "." +
  286. ((addr >> 24) & 0xff).ToString ();
  287. }
  288. /// <returns>
  289. /// Whether both objects are equal.
  290. /// </returns>
  291. public override bool Equals (object other)
  292. {
  293. if (other is System.Net.IPAddress){
  294. IPAddress otherAddr = other as IPAddress;
  295. if(AddressFamily != otherAddr.AddressFamily)
  296. return false;
  297. if(AddressFamily == AddressFamily.InterNetwork)
  298. return Address == otherAddr.Address;
  299. else
  300. {
  301. ushort[] vals = otherAddr._numbers;
  302. for(int i=0; i<8; i++)
  303. if(_numbers[i] != vals[i])
  304. return false;
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. public override int GetHashCode ()
  311. {
  312. if(_family == AddressFamily.InterNetwork)
  313. return (int)Address;
  314. else
  315. return Hash (((((int) _numbers[0]) << 16) + _numbers [1]),
  316. ((((int) _numbers [2]) << 16) + _numbers [3]),
  317. ((((int) _numbers [4]) << 16) + _numbers [5]),
  318. ((((int) _numbers [6]) << 16) + _numbers [7]));
  319. }
  320. private static int Hash (int i, int j, int k, int l)
  321. {
  322. return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
  323. }
  324. }
  325. }