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