2 // System.Net.IPAddress.cs
5 // Miguel de Icaza (miguel@ximian.com)
6 // Lawrence Pit (loz@cable.a2000.nl)
8 // (C) Ximian, Inc. http://www.ximian.com
11 // Note: the address is stored in host order
14 using System.Globalization;
15 using System.Net.Sockets;
16 using System.Runtime.InteropServices;
18 namespace System.Net {
21 /// Encapsulates an IP Address.
24 public class IPAddress {
25 // Don't change the name of this field without also
26 // changing socket-io.c in the runtime
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;
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");
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 ("::");
43 private static short SwapShort (short number)
45 return (short) ( ((number >> 8) & 0xFF) + ((number << 8) & 0xFF00) );
48 private static int SwapInt (int number)
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);
57 private static long SwapLong (long number)
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);
70 public static short HostToNetworkOrder(short host) {
71 if (!BitConverter.IsLittleEndian)
74 return SwapShort (host);
77 public static int HostToNetworkOrder(int host) {
78 if (!BitConverter.IsLittleEndian)
81 return SwapInt (host);
84 public static long HostToNetworkOrder(long host) {
85 if (!BitConverter.IsLittleEndian)
88 return SwapLong (host);
91 public static short NetworkToHostOrder(short network) {
92 if (!BitConverter.IsLittleEndian)
95 return SwapShort (network);
98 public static int NetworkToHostOrder(int network) {
99 if (!BitConverter.IsLittleEndian)
102 return SwapInt (network);
105 public static long NetworkToHostOrder(long network) {
106 if (!BitConverter.IsLittleEndian)
109 return SwapLong (network);
113 /// Constructor from a 32-bit constant with its bytes
114 /// in network order.
116 public IPAddress (long addr)
122 public IPAddress(byte[] address) : this(address, 0)
126 public IPAddress(byte[] address, long scopeId)
128 if(address.Length != 16)
\r
129 throw new ArgumentException("address");
\r
131 Buffer.BlockCopy(address, 0, _numbers, 0, 16);
\r
132 _family = AddressFamily.InterNetworkV6;
136 internal IPAddress(ushort[] address, long scopeId)
138 _numbers = address;
\r
140 for(int i=0; i<8; i++)
\r
141 _numbers[i] = (ushort)HostToNetworkOrder((short)_numbers[i]);
\r
143 _family = AddressFamily.InterNetworkV6;
148 public static IPAddress Parse (string ip)
153 throw new ArgumentNullException ("Value cannot be null.");
156 if( (ret = ParseIPV4(ip)) == null)
157 if( (ret = ParseIPV6(ip)) == null)
158 throw new FormatException("An invalid IP address was specified.");
\r
160 if( (ret = ParseIPV4(ip)) == null)
161 throw new FormatException("An invalid IP address was specified.");
\r
166 private static IPAddress ParseIPV4 (string ip)
168 if (ip.Length == 0 || ip [0] == ' ')
169 return new IPAddress (0);
171 int pos = ip.IndexOf (' ');
173 ip = ip.Substring (0, pos);
174 else if (ip [ip.Length - 1] == '.')
177 string [] ips = ip.Split (new char [] {'.'});
181 // Make the number in network order
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]);
194 val = (byte) ((Uri.FromHex (subnet [2]) << 4) | Uri.FromHex (subnet [3]));
195 } else if (subnet.Length == 0)
198 val = Byte.Parse (subnet, NumberStyles.None);
200 if (ips.Length < 4 && i == (ips.Length - 1))
203 a |= (long) val << (i << 3);
206 return (new IPAddress (a));
207 } catch (Exception) {
213 private static IPAddress ParseIPV6 (string ip)
217 IPv6Address newIPv6Address = IPv6Address.Parse(ip);
\r
218 return new IPAddress(newIPv6Address.Address, newIPv6Address.ScopeId);
\r
220 catch (Exception) {
\r
227 public long Address
\r
230 if(_family != AddressFamily.InterNetwork)
231 throw new Exception("The attempted operation is not supported for the type of object referenced");
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");
242 if(_family != AddressFamily.InterNetwork)
243 throw new Exception("The attempted operation is not supported for the type of object referenced");
250 public long ScopeId {
\r
252 if(_family != AddressFamily.InterNetworkV6)
253 throw new Exception("The attempted operation is not supported for the type of object referenced");
258 if(_family != AddressFamily.InterNetworkV6)
259 throw new Exception("The attempted operation is not supported for the type of object referenced");
264 public byte[] GetAddressBytes()
\r
267 if(_family == AddressFamily.InterNetworkV6)
269 byte[] addressBytes = new byte[16];
\r
270 Buffer.BlockCopy(_numbers, 0, addressBytes, 0, 16);
\r
271 return addressBytes;
\r
275 return new byte[4] { (byte)(address & 0xFF),
276 (byte)((address >> 8) & 0xFF),
277 (byte)((address >> 16) & 0xFF),
278 (byte)(address >> 24) };
283 public AddressFamily AddressFamily
\r
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.
296 /// <param name="addr">Address to compare</param>
297 /// <returns></returns>
298 public static bool IsLoopback (IPAddress addr)
300 if(addr._family == AddressFamily.InterNetwork)
301 return (addr.address & 0xFF) == 127;
\r
303 for(int i=0; i<6; i++) {
304 if(addr._numbers[i] != 0)
\r
308 return NetworkToHostOrder((short)addr._numbers[7]) == 1;
313 /// Overrides System.Object.ToString to return
314 /// this object rendered in a quad-dotted notation
316 public override string ToString ()
318 if(_family == AddressFamily.InterNetwork)
319 return ToString (address);
322 ushort[] numbers = _numbers.Clone() as ushort[];
324 for(int i=0; i<numbers.Length; i++)
325 numbers[i] = (ushort)NetworkToHostOrder((short)numbers[i]);
327 return new IPv6Address(numbers).ToString();
332 /// Returns this object rendered in a quad-dotted notation
334 static string ToString (long addr)
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 ();
344 /// Whether both objects are equal.
346 public override bool Equals (object other)
348 if (other is System.Net.IPAddress){
349 IPAddress otherAddr = other as IPAddress;
351 if(AddressFamily != otherAddr.AddressFamily)
354 if(AddressFamily == AddressFamily.InterNetwork)
355 return Address == otherAddr.Address;
358 ushort[] vals = otherAddr._numbers;
\r
360 for(int i=0; i<8; i++)
\r
361 if(_numbers[i] != vals[i])
\r
370 public override int GetHashCode ()
372 if(_family == AddressFamily.InterNetwork)
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
381 private static int Hash (int i, int j, int k, int l)
\r
383 return i ^ (j << 13 | j >> 19) ^ (k << 26 | k >> 6) ^ (l << 7 | l >> 25);
\r