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