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