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);
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);
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 if( (Socket.SupportsIPv6 && newAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
324 (Socket.SupportsIPv4 && newAddress.AddressFamily == AddressFamily.InterNetwork) )
325 addrlist.Add(newAddress);
326 } catch (ArgumentNullException) {
327 /* Ignore this, as the
328 * internal call might have
329 * left some blank entries at
330 * the end of the array
335 if(addrlist.Count == 0)
336 Error_11001 (originalHostName);
338 he.AddressList = addrlist.ToArray(typeof(IPAddress)) as IPAddress[];
342 [Obsolete ("Use GetHostEntry instead")]
343 public static IPHostEntry GetHostByAddress(IPAddress address)
346 throw new ArgumentNullException ("address");
348 return GetHostByAddressFromString (address.ToString (), false);
351 [Obsolete ("Use GetHostEntry instead")]
352 public static IPHostEntry GetHostByAddress(string address)
355 throw new ArgumentNullException ("address");
357 return GetHostByAddressFromString (address, true);
360 static IPHostEntry GetHostByAddressFromString (string address, bool parse)
362 // Undocumented MS behavior: when called with IF_ANY,
363 // this should return the local host
364 if (address.Equals ("0.0.0.0")) {
365 address = "127.0.0.1";
369 // Must check the IP format, might send an exception if invalid string.
371 IPAddress.Parse (address);
374 string[] h_aliases, h_addrlist;
375 bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist);
377 Error_11001 (address);
378 return (hostent_to_IPHostEntry (address, h_name, h_aliases, h_addrlist));
382 public static IPHostEntry GetHostEntry (string hostNameOrAddress)
384 if (hostNameOrAddress == null)
385 throw new ArgumentNullException ("hostNameOrAddress");
386 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
387 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
388 "and ::0 (IPv6) are unspecified addresses. You " +
389 "cannot use them as target address.",
390 "hostNameOrAddress");
393 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
394 return GetHostEntry (addr);
396 return GetHostByName (hostNameOrAddress);
399 public static IPHostEntry GetHostEntry (IPAddress address)
402 throw new ArgumentNullException ("address");
404 return GetHostByAddressFromString (address.ToString (), false);
407 public static IPAddress [] GetHostAddresses (string hostNameOrAddress)
409 if (hostNameOrAddress == null)
410 throw new ArgumentNullException ("hostNameOrAddress");
412 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
413 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
414 "and ::0 (IPv6) are unspecified addresses. You " +
415 "cannot use them as target address.",
416 "hostNameOrAddress");
419 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
420 return new IPAddress[1] { addr };
422 return GetHostEntry (hostNameOrAddress).AddressList;
425 [Obsolete ("Use GetHostEntry instead")]
426 public static IPHostEntry GetHostByName (string hostName)
428 #if FEATURE_NO_BSD_SOCKETS
429 if (!string.IsNullOrEmpty (hostName))
430 throw new PlatformNotSupportedException ("System.Net.Dns:GetHostByName is not supported on this platform.");
431 #endif // FEATURE_NO_BSD_SOCKETS
432 if (hostName == null)
433 throw new ArgumentNullException ("hostName");
435 string[] h_aliases, h_addrlist;
437 bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist);
439 Error_11001 (hostName);
441 return(hostent_to_IPHostEntry(hostName, h_name, h_aliases, h_addrlist));
444 public static string GetHostName ()
448 bool ret = GetHostName_internal(out hostName);
451 Error_11001 (hostName);
456 [Obsolete ("Use GetHostEntry instead")]
457 public static IPHostEntry Resolve(string hostName)
459 #if FEATURE_NO_BSD_SOCKETS
460 throw new PlatformNotSupportedException ("System.Net.Dns:Resolve is not supported on this platform.");
462 if (hostName == null)
463 throw new ArgumentNullException ("hostName");
465 IPHostEntry ret = null;
468 ret = GetHostByAddress(hostName);
473 ret = GetHostByName(hostName);
476 #endif // FEATURE_NO_BSD_SOCKETS
479 public static Task<IPAddress[]> GetHostAddressesAsync (string hostNameOrAddress)
481 return Task<IPAddress[]>.Factory.FromAsync (BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
484 public static Task<IPHostEntry> GetHostEntryAsync (IPAddress address)
486 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, address, null);
489 public static Task<IPHostEntry> GetHostEntryAsync (string hostNameOrAddress)
491 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);