2009-05-16 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mcs / class / System / System.Net / IPAddress.cs
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
30 using System;
31 using System.Globalization;
32 using System.Net.Sockets;
33 using System.Runtime.InteropServices;
34
35 namespace System.Net {
36
37         /// <remarks>
38         ///   Encapsulates an IP Address.
39         /// </remarks>
40         [Serializable]
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;
50
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 ("::");
58
59                 private static short SwapShort (short number)
60                 {
61                         return (short) ( ((number >> 8) & 0xFF) | ((number << 8) & 0xFF00) );
62                 }
63
64                 private static int SwapInt (int number)
65                 {
66                         return (((number >> 24) & 0xFF)
67                                   | ((number >> 08) & 0xFF00)
68                                   | ((number << 08) & 0xFF0000)
69                                   | ((number << 24)));
70                 }
71
72                 private static long SwapLong(long number)
73                 {
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)
81                                   | ((number << 56)));
82                 }
83
84                 public static short HostToNetworkOrder(short host) {
85                         if (!BitConverter.IsLittleEndian)
86                                 return(host);
87
88                         return SwapShort (host);
89                 }
90
91                 public static int HostToNetworkOrder(int host) {
92                         if (!BitConverter.IsLittleEndian)
93                                 return(host);
94
95                         return SwapInt (host);
96                 }
97                 
98                 public static long HostToNetworkOrder(long host) {
99                         if (!BitConverter.IsLittleEndian)
100                                 return(host);
101
102                         return SwapLong (host);
103                 }
104
105                 public static short NetworkToHostOrder(short network) {
106                         if (!BitConverter.IsLittleEndian)
107                                 return(network);
108
109                         return SwapShort (network);
110                 }
111
112                 public static int NetworkToHostOrder(int network) {
113                         if (!BitConverter.IsLittleEndian)
114                                 return(network);
115
116                         return SwapInt (network);
117                 }
118
119                 public static long NetworkToHostOrder(long network) {
120                         if (!BitConverter.IsLittleEndian)
121                                 return(network);
122
123                         return SwapLong (network);
124                 }
125                 
126                 /// <summary>
127                 ///   Constructor from a 32-bit constant with the address bytes in
128                 ///   little-endian order (the lower order bytes contain the netid)
129                 /// </summary>
130                 public IPAddress (long addr)
131                 {
132                         m_Address = addr;
133                         m_Family = AddressFamily.InterNetwork;
134                 }
135
136                 public IPAddress (byte[] address)
137                 {
138                         if (address == null)
139                                 throw new ArgumentNullException ("address");
140
141                         int len = address.Length;
142
143 #if NET_2_0
144                         if (len != 16 && len != 4)
145                                 throw new ArgumentException ("An invalid IP address was specified.",
146                                         "address");
147 #else
148                         if (len != 16)
149                                 throw new ArgumentException ("address");
150 #endif
151
152                         if (len == 16) {
153                                 m_Numbers = new ushort [8];
154                                 Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
155                                 m_Family = AddressFamily.InterNetworkV6;
156                                 m_ScopeId = 0;
157                         } else {
158                                 m_Address = ((uint) address [3] << 24) + (address [2] << 16) +
159                                         (address [1] << 8) + address [0];
160                                 m_Family = AddressFamily.InterNetwork;
161                         }
162                 }
163
164                 public IPAddress(byte[] address, long scopeId)
165                 {
166                         if (address == null)
167                                 throw new ArgumentNullException ("address");
168
169                         if (address.Length != 16)
170 #if NET_2_0
171                                 throw new ArgumentException ("An invalid IP address was specified.",
172                                         "address");
173 #else
174                                 throw new ArgumentException("address");
175 #endif
176
177                         m_Numbers = new ushort [8];
178                         Buffer.BlockCopy(address, 0, m_Numbers, 0, 16);
179                         m_Family = AddressFamily.InterNetworkV6;
180                         m_ScopeId = scopeId;
181                 }
182
183                 internal IPAddress(ushort[] address, long scopeId)
184                 {
185                         m_Numbers = address;
186
187                         for(int i=0; i<8; i++)
188                                 m_Numbers[i] = (ushort)HostToNetworkOrder((short)m_Numbers[i]);
189
190                         m_Family = AddressFamily.InterNetworkV6;
191                         m_ScopeId = scopeId;
192                 }
193
194                 public static IPAddress Parse (string ipString)
195                 {
196                         IPAddress ret;
197                         if (TryParse (ipString, out ret))
198                                 return ret;
199                         throw new FormatException ("An invalid IP address was specified.");
200                 }
201
202 #if NET_2_0
203                 public
204 #else
205                 internal
206 #endif
207                 static bool TryParse (string ipString, out IPAddress address)
208                 {
209                         if (ipString == null)
210                                 throw new ArgumentNullException ("ipString");
211
212                         if ((address = ParseIPV4 (ipString)) == null)
213                                 if ((address = ParseIPV6 (ipString)) == null)
214                                         return false;
215                         return true;
216                 }
217
218                 private static IPAddress ParseIPV4 (string ip)
219                 {
220 #if ONLY_1_1
221                         if (ip.Length == 0 || ip == " ")
222                                 return new IPAddress (0);
223 #endif
224
225                         int pos = ip.IndexOf (' ');
226                         if (pos != -1) {
227 #if NET_2_0
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)
232                                                 return null;
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 ())
235 #else
236                                         foreach (char c in lastNet)
237 #endif
238                                                 if (!Uri.IsHexDigit (c))
239                                                         return null;
240                                 }
241 #endif
242                                 ip = ip.Substring (0, pos);
243                         }
244
245                         if (ip.Length == 0 || ip [ip.Length - 1] == '.')
246                                 return null;
247
248                         string [] ips = ip.Split (new char [] {'.'});
249                         if (ips.Length > 4)
250                                 return null;
251                         
252                         // Make the number in network order
253                         try {
254                                 long a = 0;
255                                 long val = 0;
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]);
262                                                 else 
263                                                         val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
264                                         } else if (subnet.Length == 0)
265                                                 return null;
266                                         else if (subnet [0] == '0') {
267                                                 // octal
268                                                 val = 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';
272                                                         else
273                                                                 return null;
274                                                 }
275                                         }
276                                         else {
277 #if NET_2_0
278                                                 if (!Int64.TryParse (subnet, NumberStyles.None, null, out val))
279                                                         return null;
280 #else
281                                                 val = long.Parse (subnet, NumberStyles.None);
282 #endif
283                                         }
284
285                                         if (i == (ips.Length - 1)) 
286                                                 i = 3;
287                                         else if (val > 0xFF)
288                                                 return null; // e.g. 256.0.0.1
289                                         for (int j = 0; val > 0; j++, val /= 0x100)
290                                                 a |= (val & 0xFF) << ((i - j) << 3);
291                                 }
292
293                                 return (new IPAddress (a));
294                         } catch (Exception) {
295                                 return null;
296                         }
297                 }
298                 
299                 private static IPAddress ParseIPV6 (string ip)
300                 {
301                         IPv6Address newIPv6Address;
302
303                         if (IPv6Address.TryParse(ip, out newIPv6Address))
304                                 return  new IPAddress (newIPv6Address.Address, newIPv6Address.ScopeId);
305                         return null;
306                 }
307
308                 [Obsolete("This property is obsolete. Use GetAddressBytes.")]
309                 public long Address 
310                 {
311                         get {
312                                 if(m_Family != AddressFamily.InterNetwork)
313                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
314
315                                 return m_Address;
316                         }
317                         set {
318                                 /* no need to do this test, ms.net accepts any value.
319                                 if (value < 0 || value > 0x00000000FFFFFFFF)
320                                         throw new ArgumentOutOfRangeException (
321                                                 "the address must be between 0 and 0xFFFFFFFF");
322                                 */
323
324                                 if(m_Family != AddressFamily.InterNetwork)
325                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
326
327                                 m_Address = value;
328                         }
329                 }
330
331                 internal long InternalIPv4Address {
332                         get { return m_Address; }
333                 }
334
335 #if NET_2_0
336                 public bool IsIPv6LinkLocal {
337                         get {
338                                 if (m_Family == AddressFamily.InterNetwork)
339                                         return false;
340                                 int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
341                                 return 0xFE80 <= v && v < 0xFEC0;
342                         }
343                 }
344
345                 public bool IsIPv6SiteLocal {
346                         get {
347                                 if (m_Family == AddressFamily.InterNetwork)
348                                         return false;
349                                 int v = NetworkToHostOrder ((short) m_Numbers [0]) & 0xFFF0;
350                                 return 0xFEC0 <= v && v < 0xFF00;
351                         }
352                 }
353
354                 public bool IsIPv6Multicast {
355                         get {
356                                 return m_Family != AddressFamily.InterNetwork &&
357                                         ((ushort) NetworkToHostOrder ((short) m_Numbers [0]) & 0xFF00) == 0xFF00;
358                         }
359                 }
360 #endif
361
362                 public long ScopeId {
363                         get {
364                                 if(m_Family != AddressFamily.InterNetworkV6)
365                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
366
367                                 return m_ScopeId;
368                         }
369                         set {
370                                 if(m_Family != AddressFamily.InterNetworkV6)
371                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
372
373                                 m_ScopeId = value;
374                         }
375                 }
376
377                 public byte [] GetAddressBytes () 
378                 {
379                         if(m_Family == AddressFamily.InterNetworkV6) {
380                                 byte [] addressBytes = new byte [16];
381                                 Buffer.BlockCopy (m_Numbers, 0, addressBytes, 0, 16);
382                                 return addressBytes;
383                         } else {
384                                 return new byte [4] { (byte)(m_Address & 0xFF),
385                                                      (byte)((m_Address >> 8) & 0xFF),
386                                                      (byte)((m_Address >> 16) & 0xFF),
387                                                      (byte)(m_Address >> 24) }; 
388                         }
389                 }
390
391                 public AddressFamily AddressFamily 
392                 {
393                         get {
394                                 return m_Family;
395                         }
396                 }
397                 
398                 
399                 /// <summary>
400                 ///   Used to tell whether an address is a loopback.
401                 ///   All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in 
402                 ///   the range 0-255, are loopback addresses.
403                 /// </summary>
404                 /// <param name="addr">Address to compare</param>
405                 /// <returns></returns>
406                 public static bool IsLoopback (IPAddress addr)
407                 {
408                         if(addr.m_Family == AddressFamily.InterNetwork)
409                                 return (addr.m_Address & 0xFF) == 127;
410                         else {
411                                 for(int i=0; i<6; i++) {
412                                         if(addr.m_Numbers[i] != 0)
413                                                 return false;
414                                 }
415
416                                 return NetworkToHostOrder((short)addr.m_Numbers[7]) == 1;
417                         }
418                 }
419
420                 /// <summary>
421                 ///   Overrides System.Object.ToString to return
422                 ///   this object rendered in a quad-dotted notation
423                 /// </summary>
424                 public override string ToString ()
425                 {
426                         if(m_Family == AddressFamily.InterNetwork)
427                                 return ToString (m_Address);
428                         else
429                         {
430                                 ushort[] numbers = m_Numbers.Clone() as ushort[];
431
432                                 for(int i=0; i<numbers.Length; i++)
433                                         numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
434
435                                 IPv6Address v6 = new IPv6Address(numbers);
436                                 v6.ScopeId = ScopeId;
437                                 return v6.ToString();
438                         }
439                 }
440
441                 /// <summary>
442                 ///   Returns this object rendered in a quad-dotted notation
443                 /// </summary>
444                 static string ToString (long addr)
445                 {
446                         // addr is in network order
447                         return  (addr & 0xff).ToString () + "." +
448                                 ((addr >> 8) & 0xff).ToString () + "." +
449                                 ((addr >> 16) & 0xff).ToString () + "." +
450                                 ((addr >> 24) & 0xff).ToString ();
451                 }
452
453                 /// <returns>
454                 ///   Whether both objects are equal.
455                 /// </returns>
456                 public override bool Equals (object other)
457                 {
458                         if (other is System.Net.IPAddress){
459                                 IPAddress otherAddr = other as IPAddress;
460
461                                 if(AddressFamily != otherAddr.AddressFamily)
462                                         return false;
463
464                                 if(AddressFamily == AddressFamily.InterNetwork) {
465                                         return m_Address == otherAddr.m_Address;
466                                 } else {
467                                         ushort[] vals = otherAddr.m_Numbers;
468
469                                         for(int i=0; i<8; i++)
470                                                 if(m_Numbers[i] != vals[i])
471                                                         return false;
472
473                                         return true;
474                                 }
475                         }
476                         return false;
477                 }
478
479                 public override int GetHashCode ()
480                 {
481                         if(m_Family == AddressFamily.InterNetwork)
482                                 return (int)m_Address;
483                         else
484                                 return Hash (((((int) m_Numbers[0]) << 16) + m_Numbers [1]), 
485                                         ((((int) m_Numbers [2]) << 16) + m_Numbers [3]),
486                                         ((((int) m_Numbers [4]) << 16) + m_Numbers [5]),
487                                         ((((int) m_Numbers [6]) << 16) + m_Numbers [7]));
488                 }
489
490                 private static int Hash (int i, int j, int k, int l) 
491                 {
492                         return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
493                 }
494
495 #pragma warning disable 169
496                 // Added for serialization compatibility with MS.NET
497                 private int m_HashCode;
498 #pragma warning restore
499                 
500         }
501 }