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 private delegate IPHostEntry GetHostByNameCallback (string hostName);
78 private delegate IPHostEntry ResolveCallback (string hostName);
79 private delegate IPHostEntry GetHostEntryNameCallback (string hostName);
80 private delegate IPHostEntry GetHostEntryIPCallback (IPAddress hostAddress);
81 private delegate IPAddress [] GetHostAddressesCallback (string hostName);
84 static void OnCompleted (object sender, SimpleResolverEventArgs e)
86 DnsAsyncResult ares = (DnsAsyncResult) e.UserToken;
87 IPHostEntry entry = e.HostEntry;
88 if (entry == null || e.ResolverError != 0) {
89 ares.SetCompleted (false, new Exception ("Error: " + e.ResolverError));
92 ares.SetCompleted (false, entry);
95 static IAsyncResult BeginAsyncCallAddresses (string host, AsyncCallback callback, object state)
97 SimpleResolverEventArgs e = new SimpleResolverEventArgs ();
98 e.Completed += OnCompleted;
100 DnsAsyncResult ares = new DnsAsyncResult (callback, state);
102 if (resolver.GetHostAddressesAsync (e) == false)
103 ares.SetCompleted (true, e.HostEntry); // Completed synchronously
107 static IAsyncResult BeginAsyncCall (string host, AsyncCallback callback, object state)
109 SimpleResolverEventArgs e = new SimpleResolverEventArgs ();
110 e.Completed += OnCompleted;
112 DnsAsyncResult ares = new DnsAsyncResult (callback, state);
114 if (resolver.GetHostEntryAsync (e) == false)
115 ares.SetCompleted (true, e.HostEntry); // Completed synchronously
119 static IPHostEntry EndAsyncCall (DnsAsyncResult ares)
122 throw new ArgumentException ("Invalid asyncResult");
123 if (!ares.IsCompleted)
124 ares.AsyncWaitHandle.WaitOne ();
125 if (ares.Exception != null)
126 throw ares.Exception;
127 IPHostEntry entry = ares.HostEntry;
128 if (entry == null || entry.AddressList == null || entry.AddressList.Length == 0)
129 Error_11001 (entry.HostName);
134 [Obsolete ("Use BeginGetHostEntry instead")]
135 public static IAsyncResult BeginGetHostByName (string hostName, AsyncCallback requestCallback, object stateObject)
137 if (hostName == null)
138 throw new ArgumentNullException ("hostName");
142 return BeginAsyncCall (hostName, requestCallback, stateObject);
145 GetHostByNameCallback c = new GetHostByNameCallback (GetHostByName);
146 return c.BeginInvoke (hostName, requestCallback, stateObject);
149 [Obsolete ("Use BeginGetHostEntry instead")]
150 public static IAsyncResult BeginResolve (string hostName, AsyncCallback requestCallback, object stateObject)
152 if (hostName == null)
153 throw new ArgumentNullException ("hostName");
157 return BeginAsyncCall (hostName, requestCallback, stateObject);
160 ResolveCallback c = new ResolveCallback (Resolve);
161 return c.BeginInvoke (hostName, requestCallback, stateObject);
164 public static IAsyncResult BeginGetHostAddresses (string hostNameOrAddress, AsyncCallback requestCallback, object state)
166 if (hostNameOrAddress == null)
167 throw new ArgumentNullException ("hostName");
168 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
169 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
170 "and ::0 (IPv6) are unspecified addresses. You " +
171 "cannot use them as target address.",
172 "hostNameOrAddress");
176 return BeginAsyncCallAddresses (hostNameOrAddress, requestCallback, state);
179 GetHostAddressesCallback c = new GetHostAddressesCallback (GetHostAddresses);
180 return c.BeginInvoke (hostNameOrAddress, requestCallback, state);
183 public static IAsyncResult BeginGetHostEntry (string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
185 if (hostNameOrAddress == null)
186 throw new ArgumentNullException ("hostName");
187 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
188 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
189 "and ::0 (IPv6) are unspecified addresses. You " +
190 "cannot use them as target address.",
191 "hostNameOrAddress");
195 return BeginAsyncCall (hostNameOrAddress, requestCallback, stateObject);
198 GetHostEntryNameCallback c = new GetHostEntryNameCallback (GetHostEntry);
199 return c.BeginInvoke (hostNameOrAddress, requestCallback, stateObject);
202 public static IAsyncResult BeginGetHostEntry (IPAddress address, AsyncCallback requestCallback, object stateObject)
205 throw new ArgumentNullException ("address");
209 return BeginAsyncCall (address.ToString (), requestCallback, stateObject);
212 GetHostEntryIPCallback c = new GetHostEntryIPCallback (GetHostEntry);
213 return c.BeginInvoke (address, requestCallback, stateObject);
216 [Obsolete ("Use EndGetHostEntry instead")]
217 public static IPHostEntry EndGetHostByName (IAsyncResult asyncResult)
219 if (asyncResult == null)
220 throw new ArgumentNullException ("asyncResult");
224 return EndAsyncCall (asyncResult as DnsAsyncResult);
227 AsyncResult async = (AsyncResult) asyncResult;
228 GetHostByNameCallback cb = (GetHostByNameCallback) async.AsyncDelegate;
229 return cb.EndInvoke(asyncResult);
232 [Obsolete ("Use EndGetHostEntry instead")]
233 public static IPHostEntry EndResolve (IAsyncResult asyncResult)
235 if (asyncResult == null)
236 throw new ArgumentNullException ("asyncResult");
240 return EndAsyncCall (asyncResult as DnsAsyncResult);
243 AsyncResult async = (AsyncResult) asyncResult;
244 ResolveCallback cb = (ResolveCallback) async.AsyncDelegate;
245 return cb.EndInvoke(asyncResult);
248 public static IPAddress [] EndGetHostAddresses (IAsyncResult asyncResult)
250 if (asyncResult == null)
251 throw new ArgumentNullException ("asyncResult");
255 IPHostEntry entry = EndAsyncCall (asyncResult as DnsAsyncResult);
258 return entry.AddressList;
262 AsyncResult async = (AsyncResult) asyncResult;
263 GetHostAddressesCallback cb = (GetHostAddressesCallback) async.AsyncDelegate;
264 return cb.EndInvoke(asyncResult);
267 public static IPHostEntry EndGetHostEntry (IAsyncResult asyncResult)
269 if (asyncResult == null)
270 throw new ArgumentNullException ("asyncResult");
274 return EndAsyncCall (asyncResult as DnsAsyncResult);
277 AsyncResult async = (AsyncResult) asyncResult;
278 if (async.AsyncDelegate is GetHostEntryIPCallback)
279 return ((GetHostEntryIPCallback) async.AsyncDelegate).EndInvoke (asyncResult);
280 GetHostEntryNameCallback cb = (GetHostEntryNameCallback) async.AsyncDelegate;
281 return cb.EndInvoke(asyncResult);
286 [MethodImplAttribute(MethodImplOptions.InternalCall)]
287 private extern static bool GetHostByName_internal(string host, out string h_name, out string[] h_aliases, out string[] h_addr_list);
289 [MethodImplAttribute(MethodImplOptions.InternalCall)]
290 private extern static bool GetHostByAddr_internal(string addr, out string h_name, out string[] h_aliases, out string[] h_addr_list);
292 [MethodImplAttribute(MethodImplOptions.InternalCall)]
293 private extern static bool GetHostName_internal(out string h_name);
296 static void Error_11001 (string hostName)
298 throw new SocketException(11001, string.Format ("Could not resolve host '{0}'", hostName));
302 private static IPHostEntry hostent_to_IPHostEntry(string originalHostName, string h_name, string[] h_aliases, string[] h_addrlist)
304 IPHostEntry he = new IPHostEntry();
305 ArrayList addrlist = new ArrayList();
307 he.HostName = h_name;
308 he.Aliases = h_aliases;
309 for(int i=0; i<h_addrlist.Length; i++) {
311 IPAddress newAddress = IPAddress.Parse(h_addrlist[i]);
313 if( (Socket.SupportsIPv6 && newAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
314 (Socket.SupportsIPv4 && newAddress.AddressFamily == AddressFamily.InterNetwork) )
315 addrlist.Add(newAddress);
316 } catch (ArgumentNullException) {
317 /* Ignore this, as the
318 * internal call might have
319 * left some blank entries at
320 * the end of the array
325 if(addrlist.Count == 0)
326 Error_11001 (originalHostName);
328 he.AddressList = addrlist.ToArray(typeof(IPAddress)) as IPAddress[];
332 [Obsolete ("Use GetHostEntry instead")]
333 public static IPHostEntry GetHostByAddress(IPAddress address)
336 throw new ArgumentNullException ("address");
338 return GetHostByAddressFromString (address.ToString (), false);
341 [Obsolete ("Use GetHostEntry instead")]
342 public static IPHostEntry GetHostByAddress(string address)
345 throw new ArgumentNullException ("address");
347 return GetHostByAddressFromString (address, true);
350 static IPHostEntry GetHostByAddressFromString (string address, bool parse)
352 // Undocumented MS behavior: when called with IF_ANY,
353 // this should return the local host
354 if (address.Equals ("0.0.0.0")) {
355 address = "127.0.0.1";
359 // Must check the IP format, might send an exception if invalid string.
361 IPAddress.Parse (address);
364 string[] h_aliases, h_addrlist;
370 java.net.InetAddress[] iaArr =
371 java.net.InetAddress.getAllByName(address);
372 if (iaArr != null && iaArr.Length > 0)
373 h_name = iaArr[0].getHostName();
374 if (iaArr != null && iaArr.Length > 0)
376 h_addrlist = new String[iaArr.Length];
377 for (int i = 0; i < h_addrlist.Length; i++)
378 h_addrlist[i] = iaArr[i].getHostAddress();
380 } catch (java.net.UnknownHostException jUHE) {
381 throw new SocketException((int)SocketError.HostNotFound, jUHE.Message);
384 bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist);
386 Error_11001 (address);
388 return (hostent_to_IPHostEntry (address, h_name, h_aliases, h_addrlist));
392 public static IPHostEntry GetHostEntry (string hostNameOrAddress)
394 if (hostNameOrAddress == null)
395 throw new ArgumentNullException ("hostNameOrAddress");
396 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
397 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
398 "and ::0 (IPv6) are unspecified addresses. You " +
399 "cannot use them as target address.",
400 "hostNameOrAddress");
403 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
404 return GetHostEntry (addr);
406 return GetHostByName (hostNameOrAddress);
409 public static IPHostEntry GetHostEntry (IPAddress address)
412 throw new ArgumentNullException ("address");
414 return GetHostByAddressFromString (address.ToString (), false);
417 public static IPAddress [] GetHostAddresses (string hostNameOrAddress)
419 if (hostNameOrAddress == null)
420 throw new ArgumentNullException ("hostNameOrAddress");
422 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
423 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
424 "and ::0 (IPv6) are unspecified addresses. You " +
425 "cannot use them as target address.",
426 "hostNameOrAddress");
429 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
430 return new IPAddress[1] { addr };
432 return GetHostEntry (hostNameOrAddress).AddressList;
435 [Obsolete ("Use GetHostEntry instead")]
436 public static IPHostEntry GetHostByName (string hostName)
438 if (hostName == null)
439 throw new ArgumentNullException ("hostName");
441 if (hostName.Length == 0)
442 hostName = "localhost";
444 java.net.InetAddress[] iaArr = java.net.InetAddress.getAllByName(hostName);
445 IPHostEntry host = new IPHostEntry();
446 if (iaArr != null && iaArr.Length > 0)
448 host.HostName = iaArr[0].getHostName();
449 IPAddress[] ipArr = new IPAddress[iaArr.Length];
450 for (int i = 0; i < iaArr.Length; i++)
451 ipArr[i] = IPAddress.Parse(iaArr[i].getHostAddress());
453 host.AddressList = ipArr;
456 } catch (java.net.UnknownHostException jUHE) {
457 throw new SocketException((int)SocketError.HostNotFound, jUHE.Message);
461 string[] h_aliases, h_addrlist;
463 bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist);
465 Error_11001 (hostName);
467 return(hostent_to_IPHostEntry(hostName, h_name, h_aliases, h_addrlist));
471 public static string GetHostName ()
474 return java.net.InetAddress.getLocalHost ().getHostName ();
478 bool ret = GetHostName_internal(out hostName);
481 Error_11001 (hostName);
487 [Obsolete ("Use GetHostEntry instead")]
488 public static IPHostEntry Resolve(string hostName)
490 if (hostName == null)
491 throw new ArgumentNullException ("hostName");
493 IPHostEntry ret = null;
496 ret = GetHostByAddress(hostName);
501 ret = GetHostByName(hostName);
507 public static Task<IPAddress[]> GetHostAddressesAsync (string hostNameOrAddress)
509 return Task<IPAddress[]>.Factory.FromAsync (BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
512 public static Task<IPHostEntry> GetHostEntryAsync (IPAddress address)
514 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, address, null);
517 public static Task<IPHostEntry> GetHostEntryAsync (string hostNameOrAddress)
519 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);