2 // System.Net.IPAddress.cs
5 // Miguel de Icaza (miguel@ximian.com)
6 // Lawrence Pit (loz@cable.a2000.nl)
8 // (C) Ximian, Inc. http://www.ximian.com
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
31 using System.Globalization;
32 using System.Net.Sockets;
33 using System.Runtime.InteropServices;
35 namespace System.Net {
38 /// Encapsulates an IP Address.
41 public class IPAddress {
42 // Don't change the name of this field without also
43 // changing socket-io.c in the runtime
44 // The IP address is stored in little-endian order inside the int,
45 // meaning the lower order bytes contain the netid
46 private long m_Address;
47 private AddressFamily m_Family;
48 private ushort[] m_Numbers; /// ip6 Stored in network order (as ip4)
49 private long m_ScopeId;
51 public static readonly IPAddress Any = new IPAddress(0);
52 public static readonly IPAddress Broadcast = IPAddress.Parse ("255.255.255.255");
53 public static readonly IPAddress Loopback = IPAddress.Parse ("127.0.0.1");
54 public static readonly IPAddress None = IPAddress.Parse ("255.255.255.255");
55 public static readonly IPAddress IPv6Any = IPAddress.ParseIPV6 ("::");
56 public static readonly IPAddress IPv6Loopback = IPAddress.ParseIPV6 ("::1");
57 public static readonly IPAddress IPv6None = IPAddress.ParseIPV6 ("::");
59 private static short SwapShort (short number)
61 return (short) ( ((number >> 8) & 0xFF) | ((number << 8) & 0xFF00) );
64 private static int SwapInt (int number)
66 return (((number >> 24) & 0xFF)
67 | ((number >> 08) & 0xFF00)
68 | ((number << 08) & 0xFF0000)
72 private static long SwapLong(long number)
74 return (((number >> 56) & 0xFF)
75 | ((number >> 40) & 0xFF00)
76 | ((number >> 24) & 0xFF0000)
77 | ((number >> 08) & 0xFF000000)
78 | ((number << 08) & 0xFF00000000)
79 | ((number << 24) & 0xFF0000000000)
80 | ((number << 40) & 0xFF000000000000)
84 public static short HostToNetworkOrder(short host) {
85 if (!BitConverter.IsLittleEndian)
88 return SwapShort (host);
91 public static int HostToNetworkOrder(int host) {
92 if (!BitConverter.IsLittleEndian)
95 return SwapInt (host);
98 public static long HostToNetworkOrder(long host) {
99 if (!BitConverter.IsLittleEndian)
102 return SwapLong (host);
105 public static short NetworkToHostOrder(short network) {
106 if (!BitConverter.IsLittleEndian)
109 return SwapShort (network);
112 public static int NetworkToHostOrder(int network) {
113 if (!BitConverter.IsLittleEndian)
116 return SwapInt (network);
119 public static long NetworkToHostOrder(long network) {
120 if (!BitConverter.IsLittleEndian)
123 return SwapLong (network);
127 /// Constructor from a 32-bit constant with the address bytes in
128 /// little-endian order (the lower order bytes contain the netid)
130 public IPAddress (long newAddress)
132 m_Address = newAddress;
133 m_Family = AddressFamily.InterNetwork;
136 public IPAddress (byte[] address)
139 throw new ArgumentNullException ("address");
141 int len = address.Length;
144 if (len != 16 && len != 4)
145 throw new ArgumentException ("An invalid IP address was specified.",
149 throw new ArgumentException ("address");
153 m_Numbers = new ushort [8];
154 Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
155 m_Family = AddressFamily.InterNetworkV6;
158 m_Address = ((uint) address [3] << 24) + (address [2] << 16) +
159 (address [1] << 8) + address [0];
160 m_Family = AddressFamily.InterNetwork;
164 public IPAddress(byte[] address, long scopeid)
167 throw new ArgumentNullException ("address");
169 if (address.Length != 16)
171 throw new ArgumentException ("An invalid IP address was specified.",
174 throw new ArgumentException("address");
177 m_Numbers = new ushort [8];
178 Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
179 m_Family = AddressFamily.InterNetworkV6;
183 internal IPAddress(ushort[] address, long scopeId)
187 for(int i=0; i<8; i++)
188 m_Numbers[i] = (ushort)HostToNetworkOrder((short)m_Numbers[i]);
190 m_Family = AddressFamily.InterNetworkV6;
194 public static IPAddress Parse (string ipString)
197 if (TryParse (ipString, out ret))
199 throw new FormatException ("An invalid IP address was specified.");
207 static bool TryParse (string ipString, out IPAddress address)
209 if (ipString == null)
210 throw new ArgumentNullException ("ipString");
212 if ((address = ParseIPV4 (ipString)) == null)
213 if ((address = ParseIPV6 (ipString)) == null)
218 private static IPAddress ParseIPV4 (string ip)
221 if (ip.Length == 0 || ip == " ")
222 return new IPAddress (0);
225 int pos = ip.IndexOf (' ');
228 string [] nets = ip.Substring (pos + 1).Split (new char [] {'.'});
229 if (nets.Length > 0) {
230 string lastNet = nets [nets.Length - 1];
231 if (lastNet.Length == 0)
233 #if NET_2_1 //workaround for smcs, as it generate code that can't access string.GetEnumerator ()
234 foreach (char c in lastNet.ToCharArray ())
236 foreach (char c in lastNet)
238 if (!Uri.IsHexDigit (c))
242 ip = ip.Substring (0, pos);
245 if (ip.Length == 0 || ip [ip.Length - 1] == '.')
248 string [] ips = ip.Split (new char [] {'.'});
252 // Make the number in network order
256 for (int i = 0; i < ips.Length; i++) {
257 string subnet = ips [i];
258 if ((3 <= subnet.Length && subnet.Length <= 4) &&
259 (subnet [0] == '0') && (subnet [1] == 'x' || subnet [1] == 'X')) {
260 if (subnet.Length == 3)
261 val = (byte) Uri.FromHex (subnet [2]);
263 val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
264 } else if (subnet.Length == 0)
266 else if (subnet [0] == '0') {
269 for (int j = 1; j < subnet.Length; j++) {
270 if ('0' <= subnet [j] && subnet [j] <= '7')
271 val = (val << 3) + subnet [j] - '0';
278 if (!Int64.TryParse (subnet, NumberStyles.None, null, out val))
281 val = long.Parse (subnet, NumberStyles.None);
285 if (i == (ips.Length - 1)) {
286 if (i != 0 && val >= (256 << ((3 - i) * 8)))
288 else if (val > 0x3fffffffe) // this is the last number that parses correctly with MS
291 } else if (val >= 0x100)
293 for (int j = 0; val > 0; j++, val /= 0x100)
294 a |= (val & 0xFF) << ((i - j) << 3);
297 return (new IPAddress (a));
298 } catch (Exception) {
303 private static IPAddress ParseIPV6 (string ip)
305 IPv6Address newIPv6Address;
307 if (IPv6Address.TryParse(ip, out newIPv6Address))
308 return new IPAddress (newIPv6Address.Address, newIPv6Address.ScopeId);
312 [Obsolete("This property is obsolete. Use GetAddressBytes.")]
316 if(m_Family != AddressFamily.InterNetwork)
317 throw new Exception("The attempted operation is not supported for the type of object referenced");
322 /* no need to do this test, ms.net accepts any value.
323 if (value < 0 || value > 0x00000000FFFFFFFF)
324 throw new ArgumentOutOfRangeException (
325 "the address must be between 0 and 0xFFFFFFFF");
328 if(m_Family != AddressFamily.InterNetwork)
329 throw new Exception("The attempted operation is not supported for the type of object referenced");
335 internal long InternalIPv4Address {
336 get { return m_Address; }
340 public bool IsIPv6LinkLocal {
342 if (m_Family == AddressFamily.InterNetwork)
344 int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
345 return 0xFE80 <= v && v < 0xFEC0;
349 public bool IsIPv6SiteLocal {
351 if (m_Family == AddressFamily.InterNetwork)
353 int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
354 return 0xFEC0 <= v && v < 0xFF00;
358 public bool IsIPv6Multicast {
360 return m_Family != AddressFamily.InterNetwork &&
361 ((ushort) NetworkToHostOrder ((short) m_Numbers [0]) & 0xFF00) == 0xFF00;
366 public long ScopeId {
368 if (m_Family != AddressFamily.InterNetworkV6)
369 throw new SocketException ((int) SocketError.OperationNotSupported);
374 if (m_Family != AddressFamily.InterNetworkV6)
375 throw new SocketException ((int) SocketError.OperationNotSupported);
376 if ((value < 0) || (value > UInt32.MaxValue))
377 throw new ArgumentOutOfRangeException ();
383 public byte [] GetAddressBytes ()
385 if(m_Family == AddressFamily.InterNetworkV6) {
386 byte [] addressBytes = new byte [16];
387 Buffer.BlockCopy (m_Numbers, 0, addressBytes, 0, 16);
390 return new byte [4] { (byte)(m_Address & 0xFF),
391 (byte)((m_Address >> 8) & 0xFF),
392 (byte)((m_Address >> 16) & 0xFF),
393 (byte)(m_Address >> 24) };
397 public AddressFamily AddressFamily
406 /// Used to tell whether an address is a loopback.
407 /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
408 /// the range 0-255, are loopback addresses.
410 /// <param name="addr">Address to compare</param>
411 /// <returns></returns>
412 public static bool IsLoopback (IPAddress address)
415 // even 4.0 throws an NRE
417 throw new ArgumentNullException ("address");
419 if(address.m_Family == AddressFamily.InterNetwork)
420 return (address.m_Address & 0xFF) == 127;
422 for(int i=0; i<6; i++) {
423 if(address.m_Numbers[i] != 0)
427 return NetworkToHostOrder((short)address.m_Numbers[7]) == 1;
432 /// Overrides System.Object.ToString to return
433 /// this object rendered in a quad-dotted notation
435 public override string ToString ()
437 if(m_Family == AddressFamily.InterNetwork)
438 return ToString (m_Address);
441 ushort[] numbers = m_Numbers.Clone() as ushort[];
443 for(int i=0; i<numbers.Length; i++)
444 numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
446 IPv6Address v6 = new IPv6Address(numbers);
447 v6.ScopeId = ScopeId;
448 return v6.ToString();
453 /// Returns this object rendered in a quad-dotted notation
455 static string ToString (long addr)
457 // addr is in network order
458 return (addr & 0xff).ToString () + "." +
459 ((addr >> 8) & 0xff).ToString () + "." +
460 ((addr >> 16) & 0xff).ToString () + "." +
461 ((addr >> 24) & 0xff).ToString ();
465 /// Whether both objects are equal.
467 public override bool Equals (object comparand)
469 IPAddress otherAddr = comparand as IPAddress;
470 if (otherAddr != null){
471 if(AddressFamily != otherAddr.AddressFamily)
474 if(AddressFamily == AddressFamily.InterNetwork) {
475 return m_Address == otherAddr.m_Address;
477 ushort[] vals = otherAddr.m_Numbers;
479 for(int i=0; i<8; i++)
480 if(m_Numbers[i] != vals[i])
489 public override int GetHashCode ()
491 if(m_Family == AddressFamily.InterNetwork)
492 return (int)m_Address;
494 return Hash (((((int) m_Numbers[0]) << 16) + m_Numbers [1]),
495 ((((int) m_Numbers [2]) << 16) + m_Numbers [3]),
496 ((((int) m_Numbers [4]) << 16) + m_Numbers [5]),
497 ((((int) m_Numbers [6]) << 16) + m_Numbers [7]));
500 private static int Hash (int i, int j, int k, int l)
502 return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
505 #pragma warning disable 169
506 // Added for serialization compatibility with MS.NET
507 private int m_HashCode;
508 #pragma warning restore