4 // Mads Pultz (mpultz@diku.dk)
5 // Lawrence Pit (loz@cable.a2000.nl)
7 // Author: Mads Pultz (mpultz@diku.dk)
8 // Lawrence Pit (loz@cable.a2000.nl)
9 // Marek Safar (marek.safar@gmail.com)
10 // Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
12 // (C) Mads Pultz, 2001
13 // Copyright (c) 2011 Novell, Inc.
14 // Copyright (c) 2011 Xamarin, Inc.
17 // Permission is hereby granted, free of charge, to any person obtaining
18 // a copy of this software and associated documentation files (the
19 // "Software"), to deal in the Software without restriction, including
20 // without limitation the rights to use, copy, modify, merge, publish,
21 // distribute, sublicense, and/or sell copies of the Software, and to
22 // permit persons to whom the Software is furnished to do so, subject to
23 // the following conditions:
25 // The above copyright notice and this permission notice shall be
26 // included in all copies or substantial portions of the Software.
28 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
29 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
30 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
31 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
32 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
33 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
34 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 using System.Net.Sockets;
40 using System.Collections;
41 using System.Threading;
42 using System.Runtime.CompilerServices;
43 using System.Runtime.Remoting.Messaging;
44 using System.Threading.Tasks;
50 namespace System.Net {
51 public static class Dns {
53 static bool use_mono_dns;
54 static SimpleResolver resolver;
60 if (Environment.GetEnvironmentVariable ("MONO_DNS") != null) {
61 resolver = new SimpleResolver ();
68 internal static bool UseMonoDns {
69 get { return use_mono_dns; }
73 private delegate IPHostEntry GetHostByNameCallback (string hostName);
74 private delegate IPHostEntry ResolveCallback (string hostName);
75 private delegate IPHostEntry GetHostEntryNameCallback (string hostName);
76 private delegate IPHostEntry GetHostEntryIPCallback (IPAddress hostAddress);
77 private delegate IPAddress [] GetHostAddressesCallback (string hostName);
80 static void OnCompleted (object sender, SimpleResolverEventArgs e)
82 DnsAsyncResult ares = (DnsAsyncResult) e.UserToken;
83 IPHostEntry entry = e.HostEntry;
84 if (entry == null || e.ResolverError != 0) {
85 ares.SetCompleted (false, new Exception ("Error: " + e.ResolverError));
88 ares.SetCompleted (false, entry);
91 static IAsyncResult BeginAsyncCallAddresses (string host, AsyncCallback callback, object state)
93 SimpleResolverEventArgs e = new SimpleResolverEventArgs ();
94 e.Completed += OnCompleted;
96 DnsAsyncResult ares = new DnsAsyncResult (callback, state);
98 if (resolver.GetHostAddressesAsync (e) == false)
99 ares.SetCompleted (true, e.HostEntry); // Completed synchronously
103 static IAsyncResult BeginAsyncCall (string host, AsyncCallback callback, object state)
105 SimpleResolverEventArgs e = new SimpleResolverEventArgs ();
106 e.Completed += OnCompleted;
108 DnsAsyncResult ares = new DnsAsyncResult (callback, state);
110 if (resolver.GetHostEntryAsync (e) == false)
111 ares.SetCompleted (true, e.HostEntry); // Completed synchronously
115 static IPHostEntry EndAsyncCall (DnsAsyncResult ares)
118 throw new ArgumentException ("Invalid asyncResult");
119 if (!ares.IsCompleted)
120 ares.AsyncWaitHandle.WaitOne ();
121 if (ares.Exception != null)
122 throw ares.Exception;
123 IPHostEntry entry = ares.HostEntry;
124 if (entry == null || entry.AddressList == null || entry.AddressList.Length == 0)
125 Error_11001 (entry.HostName);
130 [Obsolete ("Use BeginGetHostEntry instead")]
131 public static IAsyncResult BeginGetHostByName (string hostName, AsyncCallback requestCallback, object stateObject)
133 #if FEATURE_NO_BSD_SOCKETS
134 throw new PlatformNotSupportedException ("System.Net.Dns:BeginGetHostByName is not supported on this platform.");
136 if (hostName == null)
137 throw new ArgumentNullException ("hostName");
141 return BeginAsyncCall (hostName, requestCallback, stateObject);
144 GetHostByNameCallback c = new GetHostByNameCallback (GetHostByName);
145 return c.BeginInvoke (hostName, requestCallback, stateObject);
146 #endif // FEATURE_NO_BSD_SOCKETS
149 [Obsolete ("Use BeginGetHostEntry instead")]
150 public static IAsyncResult BeginResolve (string hostName, AsyncCallback requestCallback, object stateObject)
152 #if FEATURE_NO_BSD_SOCKETS
153 throw new PlatformNotSupportedException ("System.Net.Dns:BeginResolve is not supported on this platform.");
155 if (hostName == null)
156 throw new ArgumentNullException ("hostName");
160 return BeginAsyncCall (hostName, requestCallback, stateObject);
163 ResolveCallback c = new ResolveCallback (Resolve);
164 return c.BeginInvoke (hostName, requestCallback, stateObject);
165 #endif // FEATURE_NO_BSD_SOCKETS
168 public static IAsyncResult BeginGetHostAddresses (string hostNameOrAddress, AsyncCallback requestCallback, object state)
170 if (hostNameOrAddress == null)
171 throw new ArgumentNullException ("hostName");
172 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
173 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
174 "and ::0 (IPv6) are unspecified addresses. You " +
175 "cannot use them as target address.",
176 "hostNameOrAddress");
180 return BeginAsyncCallAddresses (hostNameOrAddress, requestCallback, state);
183 GetHostAddressesCallback c = new GetHostAddressesCallback (GetHostAddresses);
184 return c.BeginInvoke (hostNameOrAddress, requestCallback, state);
187 public static IAsyncResult BeginGetHostEntry (string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
189 #if FEATURE_NO_BSD_SOCKETS
190 throw new PlatformNotSupportedException ("System.Net.Dns:GetHostEntry is not supported on this platform.");
192 if (hostNameOrAddress == null)
193 throw new ArgumentNullException ("hostName");
194 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
195 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
196 "and ::0 (IPv6) are unspecified addresses. You " +
197 "cannot use them as target address.",
198 "hostNameOrAddress");
202 return BeginAsyncCall (hostNameOrAddress, requestCallback, stateObject);
205 GetHostEntryNameCallback c = new GetHostEntryNameCallback (GetHostEntry);
206 return c.BeginInvoke (hostNameOrAddress, requestCallback, stateObject);
207 #endif // FEATURE_NO_BSD_SOCKETS
210 public static IAsyncResult BeginGetHostEntry (IPAddress address, AsyncCallback requestCallback, object stateObject)
212 #if FEATURE_NO_BSD_SOCKETS
213 throw new PlatformNotSupportedException ("System.Net.Dns:BeginGetHostEntry is not supported on this platform.");
216 throw new ArgumentNullException ("address");
220 return BeginAsyncCall (address.ToString (), requestCallback, stateObject);
223 GetHostEntryIPCallback c = new GetHostEntryIPCallback (GetHostEntry);
224 return c.BeginInvoke (address, requestCallback, stateObject);
225 #endif // FEATURE_NO_BSD_SOCKETS
228 [Obsolete ("Use EndGetHostEntry instead")]
229 public static IPHostEntry EndGetHostByName (IAsyncResult asyncResult)
231 if (asyncResult == null)
232 throw new ArgumentNullException ("asyncResult");
236 return EndAsyncCall (asyncResult as DnsAsyncResult);
239 AsyncResult async = (AsyncResult) asyncResult;
240 GetHostByNameCallback cb = (GetHostByNameCallback) async.AsyncDelegate;
241 return cb.EndInvoke(asyncResult);
244 [Obsolete ("Use EndGetHostEntry instead")]
245 public static IPHostEntry EndResolve (IAsyncResult asyncResult)
247 if (asyncResult == null)
248 throw new ArgumentNullException ("asyncResult");
252 return EndAsyncCall (asyncResult as DnsAsyncResult);
255 AsyncResult async = (AsyncResult) asyncResult;
256 ResolveCallback cb = (ResolveCallback) async.AsyncDelegate;
257 return cb.EndInvoke(asyncResult);
260 public static IPAddress [] EndGetHostAddresses (IAsyncResult asyncResult)
262 if (asyncResult == null)
263 throw new ArgumentNullException ("asyncResult");
267 IPHostEntry entry = EndAsyncCall (asyncResult as DnsAsyncResult);
270 return entry.AddressList;
274 AsyncResult async = (AsyncResult) asyncResult;
275 GetHostAddressesCallback cb = (GetHostAddressesCallback) async.AsyncDelegate;
276 return cb.EndInvoke(asyncResult);
279 public static IPHostEntry EndGetHostEntry (IAsyncResult asyncResult)
281 if (asyncResult == null)
282 throw new ArgumentNullException ("asyncResult");
286 return EndAsyncCall (asyncResult as DnsAsyncResult);
289 AsyncResult async = (AsyncResult) asyncResult;
290 if (async.AsyncDelegate is GetHostEntryIPCallback)
291 return ((GetHostEntryIPCallback) async.AsyncDelegate).EndInvoke (asyncResult);
292 GetHostEntryNameCallback cb = (GetHostEntryNameCallback) async.AsyncDelegate;
293 return cb.EndInvoke(asyncResult);
297 [MethodImplAttribute(MethodImplOptions.InternalCall)]
298 private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list, int hint);
300 [MethodImplAttribute(MethodImplOptions.InternalCall)]
301 private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list, int hint);
303 [MethodImplAttribute(MethodImplOptions.InternalCall)]
304 private extern static bool GetHostName_internal(out string h_name);
306 static void Error_11001 (string hostName)
308 throw new SocketException(11001, string.Format ("Could not resolve host '{0}'", hostName));
312 private static IPHostEntry hostent_to_IPHostEntry(string originalHostName, string h_name, string[] h_aliases, string[] h_addrlist)
314 IPHostEntry he = new IPHostEntry();
315 ArrayList addrlist = new ArrayList();
317 he.HostName = h_name;
318 he.Aliases = h_aliases;
319 for(int i=0; i<h_addrlist.Length; i++) {
321 IPAddress newAddress = IPAddress.Parse(h_addrlist[i]);
323 #pragma warning disable 618
324 if( (Socket.SupportsIPv6 && newAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
325 (Socket.SupportsIPv4 && newAddress.AddressFamily == AddressFamily.InterNetwork) )
326 addrlist.Add(newAddress);
327 #pragma warning restore 618
328 } catch (ArgumentNullException) {
329 /* Ignore this, as the
330 * internal call might have
331 * left some blank entries at
332 * the end of the array
337 if(addrlist.Count == 0)
338 Error_11001 (originalHostName);
340 he.AddressList = addrlist.ToArray(typeof(IPAddress)) as IPAddress[];
344 [Obsolete ("Use GetHostEntry instead")]
345 public static IPHostEntry GetHostByAddress(IPAddress address)
348 throw new ArgumentNullException ("address");
350 return GetHostByAddressFromString (address.ToString (), false);
353 [Obsolete ("Use GetHostEntry instead")]
354 public static IPHostEntry GetHostByAddress(string address)
357 throw new ArgumentNullException ("address");
359 return GetHostByAddressFromString (address, true);
362 static IPHostEntry GetHostByAddressFromString (string address, bool parse)
364 // Undocumented MS behavior: when called with IF_ANY,
365 // this should return the local host
366 if (address.Equals ("0.0.0.0")) {
367 address = "127.0.0.1";
371 // Must check the IP format, might send an exception if invalid string.
373 IPAddress.Parse (address);
376 string[] h_aliases, h_addrlist;
377 bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist, Socket.FamilyHint);
379 Error_11001 (address);
380 return (hostent_to_IPHostEntry (address, h_name, h_aliases, h_addrlist));
384 public static IPHostEntry GetHostEntry (string hostNameOrAddress)
386 if (hostNameOrAddress == null)
387 throw new ArgumentNullException ("hostNameOrAddress");
388 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
389 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
390 "and ::0 (IPv6) are unspecified addresses. You " +
391 "cannot use them as target address.",
392 "hostNameOrAddress");
395 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
396 return GetHostEntry (addr);
398 #pragma warning disable 618
399 return GetHostByName (hostNameOrAddress);
400 #pragma warning restore 618
403 public static IPHostEntry GetHostEntry (IPAddress address)
406 throw new ArgumentNullException ("address");
408 return GetHostByAddressFromString (address.ToString (), false);
411 public static IPAddress [] GetHostAddresses (string hostNameOrAddress)
413 if (hostNameOrAddress == null)
414 throw new ArgumentNullException ("hostNameOrAddress");
416 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
417 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
418 "and ::0 (IPv6) are unspecified addresses. You " +
419 "cannot use them as target address.",
420 "hostNameOrAddress");
423 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
424 return new IPAddress[1] { addr };
426 return GetHostEntry (hostNameOrAddress).AddressList;
429 [Obsolete ("Use GetHostEntry instead")]
430 public static IPHostEntry GetHostByName (string hostName)
432 #if FEATURE_NO_BSD_SOCKETS
433 if (!string.IsNullOrEmpty (hostName))
434 throw new PlatformNotSupportedException ("System.Net.Dns:GetHostByName is not supported on this platform.");
435 #endif // FEATURE_NO_BSD_SOCKETS
436 if (hostName == null)
437 throw new ArgumentNullException ("hostName");
439 string[] h_aliases, h_addrlist;
441 bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist, Socket.FamilyHint);
443 Error_11001 (hostName);
445 return(hostent_to_IPHostEntry(hostName, h_name, h_aliases, h_addrlist));
448 public static string GetHostName ()
452 bool ret = GetHostName_internal(out hostName);
455 Error_11001 (hostName);
460 [Obsolete ("Use GetHostEntry instead")]
461 public static IPHostEntry Resolve(string hostName)
463 #if FEATURE_NO_BSD_SOCKETS
464 throw new PlatformNotSupportedException ("System.Net.Dns:Resolve is not supported on this platform.");
466 if (hostName == null)
467 throw new ArgumentNullException ("hostName");
469 IPHostEntry ret = null;
472 ret = GetHostByAddress(hostName);
477 ret = GetHostByName(hostName);
480 #endif // FEATURE_NO_BSD_SOCKETS
483 public static Task<IPAddress[]> GetHostAddressesAsync (string hostNameOrAddress)
485 return Task<IPAddress[]>.Factory.FromAsync (BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
488 public static Task<IPHostEntry> GetHostEntryAsync (IPAddress address)
490 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, address, null);
493 public static Task<IPHostEntry> GetHostEntryAsync (string hostNameOrAddress)
495 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);