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 = AddressFamily.InterNetwork;
48 private ushort[] m_Numbers = new ushort[8]; /// ip6 Stored in network order (as ip4)
49 private long m_ScopeId = 0;
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 byte b0 = (byte) ((number >> 24) & 0xFF);
67 byte b1 = (byte) ((number >> 16) & 0xFF);
68 byte b2 = (byte) ((number >> 8) & 0xFF);
69 byte b3 = (byte) (number & 0xFF);
70 return b0 + (b1 << 8) + (b2 << 16) + (b3 << 24);
73 private static long SwapLong (long number)
75 byte b0 = (byte) ((number >> 56) & 0xFF);
76 byte b1 = (byte) ((number >> 48) & 0xFF);
77 byte b2 = (byte) ((number >> 40) & 0xFF);
78 byte b3 = (byte) ((number >> 32) & 0xFF);
79 byte b4 = (byte) ((number >> 24) & 0xFF);
80 byte b5 = (byte) ((number >> 16) & 0xFF);
81 byte b6 = (byte) ((number >> 8) & 0xFF);
82 byte b7 = (byte) (number & 0xFF);
83 return (long) b0 + ((long) b1 << 8) + ((long) b2 << 16) + ((long) b3 << 24) + ((long) b4 << 32) + ((long) b5 << 40) + ((long) b6 << 48) + ((long) b7 << 56);
86 public static short HostToNetworkOrder(short host) {
87 if (!BitConverter.IsLittleEndian)
90 return SwapShort (host);
93 public static int HostToNetworkOrder(int host) {
94 if (!BitConverter.IsLittleEndian)
97 return SwapInt (host);
100 public static long HostToNetworkOrder(long host) {
101 if (!BitConverter.IsLittleEndian)
104 return SwapLong (host);
107 public static short NetworkToHostOrder(short network) {
108 if (!BitConverter.IsLittleEndian)
111 return SwapShort (network);
114 public static int NetworkToHostOrder(int network) {
115 if (!BitConverter.IsLittleEndian)
118 return SwapInt (network);
121 public static long NetworkToHostOrder(long network) {
122 if (!BitConverter.IsLittleEndian)
125 return SwapLong (network);
129 /// Constructor from a 32-bit constant with the address bytes in
130 /// little-endian order (the lower order bytes contain the netid)
132 public IPAddress (long addr)
137 public IPAddress (byte[] address)
140 throw new ArgumentNullException ("address");
142 int len = address.Length;
145 if (len != 16 && len != 4)
146 throw new ArgumentException ("address");
149 throw new ArgumentException ("address");
153 Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
154 m_Family = AddressFamily.InterNetworkV6;
157 m_Address = (address [3] << 24) + (address [2] << 16) +
158 (address [1] << 8) + address [0];
162 public IPAddress(byte[] address, long scopeId)
165 throw new ArgumentNullException ("address");
167 if (address.Length != 16)
168 throw new ArgumentException("address");
170 Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
171 m_Family = AddressFamily.InterNetworkV6;
175 internal IPAddress(ushort[] address, long scopeId)
179 for(int i=0; i<8; i++)
180 m_Numbers[i] = (ushort)HostToNetworkOrder((short)m_Numbers[i]);
182 m_Family = AddressFamily.InterNetworkV6;
186 public static IPAddress Parse (string ip)
189 if (TryParse (ip, out ret))
191 throw new FormatException("An invalid IP address was specified.");
197 static bool TryParse (string ip, out IPAddress address)
200 throw new ArgumentNullException ("Value cannot be null.");
202 if( (address = ParseIPV4(ip)) == null)
203 if( (address = ParseIPV6(ip)) == null)
208 private static IPAddress ParseIPV4 (string ip)
210 if (ip.Length == 0 || ip == " ")
211 return new IPAddress (0);
213 int pos = ip.IndexOf (' ');
215 ip = ip.Substring (0, pos);
217 if (ip.Length == 0 || ip [ip.Length - 1] == '.')
220 string [] ips = ip.Split (new char [] {'.'});
224 // Make the number in network order
229 for (int i = 0; i < ips.Length; i++) {
230 string subnet = ips [i];
231 if ((3 <= subnet.Length && subnet.Length <= 4) &&
232 (subnet [0] == '0') &&
233 (subnet [1] == 'x' || subnet [2] == 'X')) {
234 if (subnet.Length == 3)
235 val = (byte) Uri.FromHex (subnet [2]);
237 val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
238 } else if (subnet.Length == 0)
241 val = Byte.Parse (subnet, NumberStyles.None);
243 if (ips.Length < 4 && i == (ips.Length - 1))
246 a |= (long) val << (i << 3);
249 return (new IPAddress (a));
250 } catch (Exception) {
255 private static IPAddress ParseIPV6 (string ip)
259 IPv6Address newIPv6Address = IPv6Address.Parse(ip);
260 return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);
267 [Obsolete("This property is obsolete. Use GetAddressBytes.")]
271 if(m_Family != AddressFamily.InterNetwork)
272 throw new Exception("The attempted operation is not supported for the type of object referenced");
277 /* no need to do this test, ms.net accepts any value.
278 if (value < 0 || value > 0x00000000FFFFFFFF)
279 throw new ArgumentOutOfRangeException (
280 "the address must be between 0 and 0xFFFFFFFF");
283 if(m_Family != AddressFamily.InterNetwork)
284 throw new Exception("The attempted operation is not supported for the type of object referenced");
290 internal long InternalIPv4Address {
291 get { return m_Address; }
295 public bool IsIPv6LinkLocal {
297 if (m_Family == AddressFamily.InterNetwork)
299 int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
300 return 0xFE80 <= v && v < 0xFEC0;
304 public bool IsIPv6SiteLocal {
306 if (m_Family == AddressFamily.InterNetwork)
308 int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
309 return 0xFEC0 <= v && v < 0xFF00;
313 public bool IsIPv6Multicast {
315 return m_Family != AddressFamily.InterNetwork &&
316 ((ushort) NetworkToHostOrder ((short) m_Numbers [0]) & 0xFF00) == 0xFF00;
321 public long ScopeId {
323 if(m_Family != AddressFamily.InterNetworkV6)
324 throw new Exception("The attempted operation is not supported for the type of object referenced");
329 if(m_Family != AddressFamily.InterNetworkV6)
330 throw new Exception("The attempted operation is not supported for the type of object referenced");
336 public byte [] GetAddressBytes ()
338 if(m_Family == AddressFamily.InterNetworkV6) {
339 byte [] addressBytes = new byte [16];
340 Buffer.BlockCopy (m_Numbers, 0, addressBytes, 0, 16);
343 return new byte [4] { (byte)(m_Address & 0xFF),
344 (byte)((m_Address >> 8) & 0xFF),
345 (byte)((m_Address >> 16) & 0xFF),
346 (byte)(m_Address >> 24) };
350 public AddressFamily AddressFamily
359 /// Used to tell whether an address is a loopback.
360 /// All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in
361 /// the range 0-255, are loopback addresses.
363 /// <param name="addr">Address to compare</param>
364 /// <returns></returns>
365 public static bool IsLoopback (IPAddress addr)
367 if(addr.m_Family == AddressFamily.InterNetwork)
368 return (addr.m_Address & 0xFF) == 127;
370 for(int i=0; i<6; i++) {
371 if(addr.m_Numbers[i] != 0)
375 return NetworkToHostOrder((short)addr.m_Numbers[7]) == 1;
380 /// Overrides System.Object.ToString to return
381 /// this object rendered in a quad-dotted notation
383 public override string ToString ()
385 if(m_Family == AddressFamily.InterNetwork)
386 return ToString (m_Address);
389 ushort[] numbers = m_Numbers.Clone() as ushort[];
391 for(int i=0; i<numbers.Length; i++)
392 numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
394 return new IPv6Address(numbers).ToString();
399 /// Returns this object rendered in a quad-dotted notation
401 static string ToString (long addr)
403 // addr is in network order
404 return (addr & 0xff).ToString () + "." +
405 ((addr >> 8) & 0xff).ToString () + "." +
406 ((addr >> 16) & 0xff).ToString () + "." +
407 ((addr >> 24) & 0xff).ToString ();
411 /// Whether both objects are equal.
413 public override bool Equals (object other)
415 if (other is System.Net.IPAddress){
416 IPAddress otherAddr = other as IPAddress;
418 if(AddressFamily != otherAddr.AddressFamily)
421 if(AddressFamily == AddressFamily.InterNetwork) {
422 return m_Address == otherAddr.m_Address;
424 ushort[] vals = otherAddr.m_Numbers;
426 for(int i=0; i<8; i++)
427 if(m_Numbers[i] != vals[i])
436 public override int GetHashCode ()
438 if(m_Family == AddressFamily.InterNetwork)
439 return (int)m_Address;
441 return Hash (((((int) m_Numbers[0]) << 16) + m_Numbers [1]),
442 ((((int) m_Numbers [2]) << 16) + m_Numbers [3]),
443 ((((int) m_Numbers [4]) << 16) + m_Numbers [5]),
444 ((((int) m_Numbers [6]) << 16) + m_Numbers [7]));
447 private static int Hash (int i, int j, int k, int l)
449 return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
452 #pragma warning disable 169
453 // Added for serialization compatibility with MS.NET
454 private int m_HashCode;
455 #pragma warning restore