Removed Consoles and ^Ms
[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 //
11 // Note: the address is stored in host order
12
13 using System;
14 using System.Globalization;
15 using System.Net.Sockets;
16 using System.Runtime.InteropServices;
17
18 namespace System.Net {
19
20         /// <remarks>
21         ///   Encapsulates an IP Address.
22         /// </remarks>
23         [Serializable]
24         public class IPAddress {
25                 // Don't change the name of this field without also
26                 // changing socket-io.c in the runtime
27                 private long address;
28                 private AddressFamily _family = AddressFamily.InterNetwork;
29                 private ushort[] _numbers = new ushort[8];      /// ip6 Stored in network order (as ip4)
30                 private long _scopeId = 0;
31
32                 public static readonly IPAddress Any = new IPAddress(0);
33                 public static readonly IPAddress Broadcast = IPAddress.Parse ("255.255.255.255");
34                 public static readonly IPAddress Loopback = IPAddress.Parse ("127.0.0.1");
35                 public static readonly IPAddress None = IPAddress.Parse ("255.255.255.255");
36
37 #if NET_1_1
38                 public static readonly IPAddress IPv6Any = IPAddress.ParseIPV6 ("::");
39                 public static readonly IPAddress IPv6Loopback = IPAddress.ParseIPV6 ("::1");
40                 public static readonly IPAddress IPv6None = IPAddress.ParseIPV6 ("::");
41 #endif
42
43                 private static short SwapShort (short number)
44                 {
45                         return (short) ( ((number >> 8) & 0xFF) + ((number << 8) & 0xFF00) );
46                 }
47
48                 private static int SwapInt (int number)
49                 {
50                         byte b0 = (byte) ((number >> 24) & 0xFF);
51                         byte b1 = (byte) ((number >> 16) & 0xFF);
52                         byte b2 = (byte) ((number >> 8) & 0xFF);
53                         byte b3 = (byte) (number & 0xFF);
54                         return b0 + (b1 << 8) + (b2 << 16) + (b3 << 24);
55                 }
56
57                 private static long SwapLong (long number)
58                 {
59                         byte b0 = (byte) ((number >> 56) & 0xFF);
60                         byte b1 = (byte) ((number >> 48) & 0xFF);
61                         byte b2 = (byte) ((number >> 40) & 0xFF);
62                         byte b3 = (byte) ((number >> 32) & 0xFF);
63                         byte b4 = (byte) ((number >> 24) & 0xFF);
64                         byte b5 = (byte) ((number >> 16) & 0xFF);
65                         byte b6 = (byte) ((number >> 8) & 0xFF);
66                         byte b7 = (byte) (number & 0xFF);
67                         return (long) b0 + ((long) b1 << 8) + ((long) b2 << 16) + ((long) b3 << 24) + ((long) b4 << 32) + ((long) b5 << 40) + ((long) b6 << 48) + ((long) b7 << 56);
68                 }
69
70                 public static short HostToNetworkOrder(short host) {
71                         if (!BitConverter.IsLittleEndian)
72                                 return(host);
73
74                         return SwapShort (host);
75                 }
76
77                 public static int HostToNetworkOrder(int host) {
78                         if (!BitConverter.IsLittleEndian)
79                                 return(host);
80
81                         return SwapInt (host);
82                 }
83                 
84                 public static long HostToNetworkOrder(long host) {
85                         if (!BitConverter.IsLittleEndian)
86                                 return(host);
87
88                         return SwapLong (host);
89                 }
90
91                 public static short NetworkToHostOrder(short network) {
92                         if (!BitConverter.IsLittleEndian)
93                                 return(network);
94
95                         return SwapShort (network);
96                 }
97
98                 public static int NetworkToHostOrder(int network) {
99                         if (!BitConverter.IsLittleEndian)
100                                 return(network);
101
102                         return SwapInt (network);
103                 }
104
105                 public static long NetworkToHostOrder(long network) {
106                         if (!BitConverter.IsLittleEndian)
107                                 return(network);
108
109                         return SwapLong (network);
110                 }
111                 
112                 /// <summary>
113                 ///   Constructor from a 32-bit constant with its bytes 
114                 ///   in network order.
115                 /// </summary>
116                 public IPAddress (long addr)
117                 {
118                         address = addr;
119                 }
120
121 #if NET_1_1
122                 public IPAddress(byte[] address) : this(address, 0)
123                 {\r
124                 }
125
126                 public IPAddress(byte[] address, long scopeId)
127                 {\r
128                         if(address.Length != 16)\r
129                                 throw new ArgumentException("address");\r
130 \r
131                         Buffer.BlockCopy(address, 0, _numbers, 0, 16);\r
132                         _family = AddressFamily.InterNetworkV6;
133                         _scopeId = scopeId;
134                 }
135
136                 internal IPAddress(ushort[] address, long scopeId)
137                 {\r
138                         _numbers = address;\r
139 \r
140                         for(int i=0; i<8; i++)\r
141                                 _numbers[i] = (ushort)HostToNetworkOrder((short)_numbers[i]);\r
142 \r
143                         _family = AddressFamily.InterNetworkV6;
144                         _scopeId = scopeId;
145                 }
146 #endif
147
148                 public static IPAddress Parse (string ip)
149                 {
150                         IPAddress ret;
151
152                         if (ip == null)
153                                 throw new ArgumentNullException ("Value cannot be null.");
154                                 
155 #if NET_1_1
156                         if( (ret = ParseIPV4(ip)) == null)
157                                 if( (ret = ParseIPV6(ip)) == null)
158                                         throw new FormatException("An invalid IP address was specified.");\r
159 #else
160                         if( (ret = ParseIPV4(ip)) == null)
161                                         throw new FormatException("An invalid IP address was specified.");\r
162 #endif
163                         return ret;
164                 }
165
166                 private static IPAddress ParseIPV4 (string ip)
167                 {\r
168                         if (ip.Length == 0 || ip [0] == ' ')
169                                 return new IPAddress (0);
170                                 
171                         int pos = ip.IndexOf (' ');
172                         if (pos != -1)
173                                 ip = ip.Substring (0, pos);                             
174                         else if (ip [ip.Length - 1] == '.')
175                                 return null;
176
177                         string [] ips = ip.Split (new char [] {'.'});
178                         if (ips.Length > 4)
179                                 return null;
180                         
181                         // Make the number in network order
182                         try \r
183                         {
184                                 long a = 0;
185                                 byte val = 0;
186                                 for (int i = 0; i < ips.Length; i++) {
187                                         string subnet = ips [i];
188                                         if ((3 <= subnet.Length && subnet.Length <= 4) &&
189                                             (subnet [0] == '0') &&
190                                             (subnet [1] == 'x' || subnet [2] == 'X')) {
191                                                 if (subnet.Length == 3)
192                                                         val = (byte) Uri.FromHex (subnet [2]);
193                                                 else 
194                                                         val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
195                                         } else if (subnet.Length == 0)
196                                                 val = 0;
197                                         else 
198                                                 val = Byte.Parse (subnet, NumberStyles.None);
199
200                                         if (ips.Length < 4 && i == (ips.Length - 1)) 
201                                                 i = 3;
202
203                                         a |= (long) val << (i << 3);
204                                 }
205
206                                 return (new IPAddress (a));
207                         } catch (Exception) {
208                                 return null;
209                         }\r
210                 }
211                 
212 #if NET_1_1
213                 private static IPAddress ParseIPV6 (string ip)
214                 {\r
215                         try \r
216                         {\r
217                                 IPv6Address newIPv6Address = IPv6Address.Parse(ip);\r
218                                 return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);\r
219                         }\r
220                         catch (Exception) {\r
221                                 return null;\r
222                         }\r
223                 }
224
225                 [Obsolete]
226 #endif
227                 public long Address \r
228                 {
229                         get {
230                                 if(_family != AddressFamily.InterNetwork)
231                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
232
233                                 return address;
234                         }
235                         set {
236                                 /* no need to do this test, ms.net accepts any value.
237                                 if (value < 0 || value > 0x00000000FFFFFFFF)
238                                         throw new ArgumentOutOfRangeException (
239                                                 "the address must be between 0 and 0xFFFFFFFF");
240                                 */
241
242                                 if(_family != AddressFamily.InterNetwork)
243                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
244
245                                 address = value;
246                         }
247                 }
248
249 #if NET_1_1
250                 public long ScopeId {\r
251                         get {\r
252                                 if(_family != AddressFamily.InterNetworkV6)
253                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
254
255                                 return _scopeId;\r
256                         }\r
257                         set {\r
258                                 if(_family != AddressFamily.InterNetworkV6)
259                                         throw new Exception("The attempted operation is not supported for the type of object referenced");
260
261                                 _scopeId = value;\r
262                         }\r
263                 }
264                 public byte[] GetAddressBytes() \r
265                 {\r
266 \r
267                         if(_family == AddressFamily.InterNetworkV6)
268                         {\r
269                                 byte[] addressBytes = new byte[16];\r
270                                 Buffer.BlockCopy(_numbers, 0, addressBytes, 0, 16);\r
271                                 return addressBytes;\r
272                         }
273                         else
274                         {\r
275                                 return new byte[4] { (byte)(address & 0xFF),
276                                                                            (byte)((address >> 8) & 0xFF),
277                                                                            (byte)((address >> 16) & 0xFF),
278                                                                            (byte)(address >> 24) }; 
279                         }
280                 }
281 #endif
282
283                 public AddressFamily AddressFamily \r
284                 {
285                         get {
286                                 return _family;
287                         }
288                 }
289                 
290                 
291                 /// <summary>
292                 ///   Used to tell whether an address is a loopback.
293                 ///   All IP addresses of the form 127.X.Y.Z, where X, Y, and Z are in 
294                 ///   the range 0-255, are loopback addresses.
295                 /// </summary>
296                 /// <param name="addr">Address to compare</param>
297                 /// <returns></returns>
298                 public static bool IsLoopback (IPAddress addr)
299                 {
300                         if(addr._family == AddressFamily.InterNetwork)
301                                 return (addr.address & 0xFF) == 127;\r
302                         else {\r
303                                 for(int i=0; i<6; i++) {
304                                         if(addr._numbers[i] != 0)\r
305                                                 return false;\r
306                                 }\r
307 \r
308                                 return NetworkToHostOrder((short)addr._numbers[7]) == 1;
309                         }
310                 }
311
312                 /// <summary>
313                 ///   Overrides System.Object.ToString to return
314                 ///   this object rendered in a quad-dotted notation
315                 /// </summary>
316                 public override string ToString ()
317                 {
318                         if(_family == AddressFamily.InterNetwork)
319                                 return ToString (address);
320                         else
321                         {
322                                 ushort[] numbers = _numbers.Clone() as ushort[];
323
324                                 for(int i=0; i<numbers.Length; i++)
325                                         numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
326
327                                 return new IPv6Address(numbers).ToString();
328                         }
329                 }
330
331                 /// <summary>
332                 ///   Returns this object rendered in a quad-dotted notation
333                 /// </summary>
334                 static string ToString (long addr)
335                 {
336                         // addr is in network order
337                         return  (addr & 0xff).ToString () + "." +
338                                 ((addr >> 8) & 0xff).ToString () + "." +
339                                 ((addr >> 16) & 0xff).ToString () + "." +
340                                 ((addr >> 24) & 0xff).ToString ();
341                 }
342
343                 /// <returns>
344                 ///   Whether both objects are equal.
345                 /// </returns>
346                 public override bool Equals (object other)
347                 {
348                         if (other is System.Net.IPAddress){
349                                 IPAddress otherAddr = other as IPAddress;
350
351                                 if(AddressFamily != otherAddr.AddressFamily)
352                                         return false;
353
354                                 if(AddressFamily == AddressFamily.InterNetwork)
355                                         return Address == otherAddr.Address;
356                                 else
357                                 {\r
358                                         ushort[] vals = otherAddr._numbers;\r
359 \r
360                                         for(int i=0; i<8; i++)\r
361                                                 if(_numbers[i] != vals[i])\r
362                                                         return false;\r
363 \r
364                                         return true;\r
365                                 }
366                         }
367                         return false;
368                 }
369
370                 public override int GetHashCode ()
371                 {
372                         if(_family == AddressFamily.InterNetwork)
373                                 return (int)Address;
374                         else
375                                 return Hash (((((int) _numbers[0]) << 16) + _numbers [1]), \r
376                                         ((((int) _numbers [2]) << 16) + _numbers [3]),\r
377                                         ((((int) _numbers [4]) << 16) + _numbers [5]),\r
378                                         ((((int) _numbers [6]) << 16) + _numbers [7]));\r
379                 }
380
381                 private static int Hash (int i, int j, int k, int l) \r
382                 {\r
383                         return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);\r
384                 }\r
385         }
386 }