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;
45 using System.Threading.Tasks;
52 namespace System.Net {
53 public static class Dns {
55 static bool use_mono_dns;
56 static SimpleResolver resolver;
61 System.Net.Sockets.Socket.CheckProtocolSupport();
64 if (Environment.GetEnvironmentVariable ("MONO_DNS") != null) {
65 resolver = new SimpleResolver ();
72 internal static bool UseMonoDns {
73 get { return use_mono_dns; }
77 #if !MOONLIGHT // global remove of async methods
80 private delegate IPHostEntry GetHostByNameCallback (string hostName);
81 private delegate IPHostEntry ResolveCallback (string hostName);
82 private delegate IPHostEntry GetHostEntryNameCallback (string hostName);
83 private delegate IPHostEntry GetHostEntryIPCallback (IPAddress hostAddress);
84 private delegate IPAddress [] GetHostAddressesCallback (string hostName);
87 static void OnCompleted (object sender, SimpleResolverEventArgs e)
89 DnsAsyncResult ares = (DnsAsyncResult) e.UserToken;
90 IPHostEntry entry = e.HostEntry;
91 if (entry == null || e.ResolverError != 0) {
92 ares.SetCompleted (false, new Exception ("Error: " + e.ResolverError));
95 ares.SetCompleted (false, entry);
98 static IAsyncResult BeginAsyncCallAddresses (string host, AsyncCallback callback, object state)
100 SimpleResolverEventArgs e = new SimpleResolverEventArgs ();
101 e.Completed += OnCompleted;
103 DnsAsyncResult ares = new DnsAsyncResult (callback, state);
105 if (resolver.GetHostAddressesAsync (e) == false)
106 ares.SetCompleted (true, e.HostEntry); // Completed synchronously
110 static IAsyncResult BeginAsyncCall (string host, AsyncCallback callback, object state)
112 SimpleResolverEventArgs e = new SimpleResolverEventArgs ();
113 e.Completed += OnCompleted;
115 DnsAsyncResult ares = new DnsAsyncResult (callback, state);
117 if (resolver.GetHostEntryAsync (e) == false)
118 ares.SetCompleted (true, e.HostEntry); // Completed synchronously
122 static IPHostEntry EndAsyncCall (DnsAsyncResult ares)
125 throw new ArgumentException ("Invalid asyncResult");
126 if (!ares.IsCompleted)
127 ares.AsyncWaitHandle.WaitOne ();
128 if (ares.Exception != null)
129 throw ares.Exception;
130 IPHostEntry entry = ares.HostEntry;
131 if (entry == null || entry.AddressList == null || entry.AddressList.Length == 0)
132 throw new SocketException(11001);
137 [Obsolete ("Use BeginGetHostEntry instead")]
138 public static IAsyncResult BeginGetHostByName (string hostName, AsyncCallback requestCallback, object stateObject)
140 if (hostName == null)
141 throw new ArgumentNullException ("hostName");
145 return BeginAsyncCall (hostName, requestCallback, stateObject);
148 GetHostByNameCallback c = new GetHostByNameCallback (GetHostByName);
149 return c.BeginInvoke (hostName, requestCallback, stateObject);
152 [Obsolete ("Use BeginGetHostEntry instead")]
153 public static IAsyncResult BeginResolve (string hostName, AsyncCallback requestCallback, object stateObject)
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);
167 public static IAsyncResult BeginGetHostAddresses (string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
169 if (hostNameOrAddress == null)
170 throw new ArgumentNullException ("hostName");
171 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
172 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
173 "and ::0 (IPv6) are unspecified addresses. You " +
174 "cannot use them as target address.",
175 "hostNameOrAddress");
179 return BeginAsyncCallAddresses (hostNameOrAddress, requestCallback, stateObject);
182 GetHostAddressesCallback c = new GetHostAddressesCallback (GetHostAddresses);
183 return c.BeginInvoke (hostNameOrAddress, requestCallback, stateObject);
186 public static IAsyncResult BeginGetHostEntry (string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
188 if (hostNameOrAddress == null)
189 throw new ArgumentNullException ("hostName");
190 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
191 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
192 "and ::0 (IPv6) are unspecified addresses. You " +
193 "cannot use them as target address.",
194 "hostNameOrAddress");
198 return BeginAsyncCall (hostNameOrAddress, requestCallback, stateObject);
201 GetHostEntryNameCallback c = new GetHostEntryNameCallback (GetHostEntry);
202 return c.BeginInvoke (hostNameOrAddress, requestCallback, stateObject);
205 public static IAsyncResult BeginGetHostEntry (IPAddress address, AsyncCallback requestCallback, object stateObject)
208 throw new ArgumentNullException ("address");
212 return BeginAsyncCall (address.ToString (), requestCallback, stateObject);
215 GetHostEntryIPCallback c = new GetHostEntryIPCallback (GetHostEntry);
216 return c.BeginInvoke (address, requestCallback, stateObject);
219 [Obsolete ("Use EndGetHostEntry instead")]
220 public static IPHostEntry EndGetHostByName (IAsyncResult asyncResult)
222 if (asyncResult == null)
223 throw new ArgumentNullException ("asyncResult");
227 return EndAsyncCall (asyncResult as DnsAsyncResult);
230 AsyncResult async = (AsyncResult) asyncResult;
231 GetHostByNameCallback cb = (GetHostByNameCallback) async.AsyncDelegate;
232 return cb.EndInvoke(asyncResult);
235 [Obsolete ("Use EndGetHostEntry instead")]
236 public static IPHostEntry EndResolve (IAsyncResult asyncResult)
238 if (asyncResult == null)
239 throw new ArgumentNullException ("asyncResult");
243 return EndAsyncCall (asyncResult as DnsAsyncResult);
246 AsyncResult async = (AsyncResult) asyncResult;
247 ResolveCallback cb = (ResolveCallback) async.AsyncDelegate;
248 return cb.EndInvoke(asyncResult);
251 public static IPAddress [] EndGetHostAddresses (IAsyncResult asyncResult)
253 if (asyncResult == null)
254 throw new ArgumentNullException ("asyncResult");
258 IPHostEntry entry = EndAsyncCall (asyncResult as DnsAsyncResult);
261 return entry.AddressList;
265 AsyncResult async = (AsyncResult) asyncResult;
266 GetHostAddressesCallback cb = (GetHostAddressesCallback) async.AsyncDelegate;
267 return cb.EndInvoke(asyncResult);
270 public static IPHostEntry EndGetHostEntry (IAsyncResult asyncResult)
272 if (asyncResult == null)
273 throw new ArgumentNullException ("asyncResult");
277 return EndAsyncCall (asyncResult as DnsAsyncResult);
280 AsyncResult async = (AsyncResult) asyncResult;
281 if (async.AsyncDelegate is GetHostEntryIPCallback)
282 return ((GetHostEntryIPCallback) async.AsyncDelegate).EndInvoke (asyncResult);
283 GetHostEntryNameCallback cb = (GetHostEntryNameCallback) async.AsyncDelegate;
284 return cb.EndInvoke(asyncResult);
287 #endif // !MOONLIGHT: global remove of async methods
290 [MethodImplAttribute(MethodImplOptions.InternalCall)]
291 private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list);
293 [MethodImplAttribute(MethodImplOptions.InternalCall)]
294 private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list);
296 [MethodImplAttribute(MethodImplOptions.InternalCall)]
297 private extern static bool GetHostName_internal(out string h_name);
300 private static IPHostEntry hostent_to_IPHostEntry(string h_name, string[] h_aliases, string[] h_addrlist)
302 IPHostEntry he = new IPHostEntry();
303 ArrayList addrlist = new ArrayList();
305 he.HostName = h_name;
306 he.Aliases = h_aliases;
307 for(int i=0; i<h_addrlist.Length; i++) {
309 IPAddress newAddress = IPAddress.Parse(h_addrlist[i]);
311 if( (Socket.SupportsIPv6 && newAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
312 (Socket.SupportsIPv4 && newAddress.AddressFamily == AddressFamily.InterNetwork) )
313 addrlist.Add(newAddress);
314 } catch (ArgumentNullException) {
315 /* Ignore this, as the
316 * internal call might have
317 * left some blank entries at
318 * the end of the array
323 if(addrlist.Count == 0)
324 throw new SocketException(11001);
326 he.AddressList = addrlist.ToArray(typeof(IPAddress)) as IPAddress[];
330 [Obsolete ("Use GetHostEntry instead")]
331 public static IPHostEntry GetHostByAddress(IPAddress address)
334 throw new ArgumentNullException ("address");
336 return GetHostByAddressFromString (address.ToString (), false);
339 [Obsolete ("Use GetHostEntry instead")]
340 public static IPHostEntry GetHostByAddress(string address)
343 throw new ArgumentNullException ("address");
345 return GetHostByAddressFromString (address, true);
348 static IPHostEntry GetHostByAddressFromString (string address, bool parse)
350 // Undocumented MS behavior: when called with IF_ANY,
351 // this should return the local host
352 if (address.Equals ("0.0.0.0")) {
353 address = "127.0.0.1";
357 // Must check the IP format, might send an exception if invalid string.
359 IPAddress.Parse (address);
362 string[] h_aliases, h_addrlist;
368 java.net.InetAddress[] iaArr =
369 java.net.InetAddress.getAllByName(address);
370 if (iaArr != null && iaArr.Length > 0)
371 h_name = iaArr[0].getHostName();
372 if (iaArr != null && iaArr.Length > 0)
374 h_addrlist = new String[iaArr.Length];
375 for (int i = 0; i < h_addrlist.Length; i++)
376 h_addrlist[i] = iaArr[i].getHostAddress();
378 } catch (java.net.UnknownHostException jUHE) {
379 throw new SocketException((int)SocketError.HostNotFound, jUHE.Message);
382 bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist);
384 throw new SocketException(11001);
386 return (hostent_to_IPHostEntry (h_name, h_aliases, h_addrlist));
390 public static IPHostEntry GetHostEntry (string hostNameOrAddress)
392 if (hostNameOrAddress == null)
393 throw new ArgumentNullException ("hostNameOrAddress");
394 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
395 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
396 "and ::0 (IPv6) are unspecified addresses. You " +
397 "cannot use them as target address.",
398 "hostNameOrAddress");
401 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
402 return GetHostEntry (addr);
404 return GetHostByName (hostNameOrAddress);
407 public static IPHostEntry GetHostEntry (IPAddress address)
410 throw new ArgumentNullException ("address");
412 return GetHostByAddressFromString (address.ToString (), false);
415 public static IPAddress [] GetHostAddresses (string hostNameOrAddress)
417 if (hostNameOrAddress == null)
418 throw new ArgumentNullException ("hostNameOrAddress");
420 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
421 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
422 "and ::0 (IPv6) are unspecified addresses. You " +
423 "cannot use them as target address.",
424 "hostNameOrAddress");
427 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
428 return new IPAddress[1] { addr };
430 return GetHostEntry (hostNameOrAddress).AddressList;
433 [Obsolete ("Use GetHostEntry instead")]
434 public static IPHostEntry GetHostByName (string hostName)
436 if (hostName == null)
437 throw new ArgumentNullException ("hostName");
439 if (hostName.Length == 0)
440 hostName = "localhost";
442 java.net.InetAddress[] iaArr = java.net.InetAddress.getAllByName(hostName);
443 IPHostEntry host = new IPHostEntry();
444 if (iaArr != null && iaArr.Length > 0)
446 host.HostName = iaArr[0].getHostName();
447 IPAddress[] ipArr = new IPAddress[iaArr.Length];
448 for (int i = 0; i < iaArr.Length; i++)
449 ipArr[i] = IPAddress.Parse(iaArr[i].getHostAddress());
451 host.AddressList = ipArr;
454 } catch (java.net.UnknownHostException jUHE) {
455 throw new SocketException((int)SocketError.HostNotFound, jUHE.Message);
459 string[] h_aliases, h_addrlist;
461 bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist);
463 throw new SocketException(11001);
465 return(hostent_to_IPHostEntry(h_name, h_aliases, h_addrlist));
469 public static string GetHostName ()
472 return java.net.InetAddress.getLocalHost ().getHostName ();
476 bool ret = GetHostName_internal(out hostName);
479 throw new SocketException(11001);
485 [Obsolete ("Use GetHostEntry instead")]
486 public static IPHostEntry Resolve(string hostName)
488 if (hostName == null)
489 throw new ArgumentNullException ("hostName");
491 IPHostEntry ret = null;
494 ret = GetHostByAddress(hostName);
499 ret = GetHostByName(hostName);
505 public static Task<IPAddress[]> GetHostAddressesAsync (string hostNameOrAddress)
507 return Task<IPAddress[]>.Factory.FromAsync (BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
510 public static Task<IPHostEntry> GetHostEntryAsync (IPAddress address)
512 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, address, null);
515 public static Task<IPHostEntry> GetHostEntryAsync (string hostNameOrAddress)
517 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);