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 throw new SocketException(11001);
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 private static IPHostEntry hostent_to_IPHostEntry(string h_name, string[] h_aliases, string[] h_addrlist)
298 IPHostEntry he = new IPHostEntry();
299 ArrayList addrlist = new ArrayList();
301 he.HostName = h_name;
302 he.Aliases = h_aliases;
303 for(int i=0; i<h_addrlist.Length; i++) {
305 IPAddress newAddress = IPAddress.Parse(h_addrlist[i]);
307 if( (Socket.SupportsIPv6 && newAddress.AddressFamily == AddressFamily.InterNetworkV6) ||
308 (Socket.SupportsIPv4 && newAddress.AddressFamily == AddressFamily.InterNetwork) )
309 addrlist.Add(newAddress);
310 } catch (ArgumentNullException) {
311 /* Ignore this, as the
312 * internal call might have
313 * left some blank entries at
314 * the end of the array
319 if(addrlist.Count == 0)
320 throw new SocketException(11001);
322 he.AddressList = addrlist.ToArray(typeof(IPAddress)) as IPAddress[];
326 [Obsolete ("Use GetHostEntry instead")]
327 public static IPHostEntry GetHostByAddress(IPAddress address)
330 throw new ArgumentNullException ("address");
332 return GetHostByAddressFromString (address.ToString (), false);
335 [Obsolete ("Use GetHostEntry instead")]
336 public static IPHostEntry GetHostByAddress(string address)
339 throw new ArgumentNullException ("address");
341 return GetHostByAddressFromString (address, true);
344 static IPHostEntry GetHostByAddressFromString (string address, bool parse)
346 // Undocumented MS behavior: when called with IF_ANY,
347 // this should return the local host
348 if (address.Equals ("0.0.0.0")) {
349 address = "127.0.0.1";
353 // Must check the IP format, might send an exception if invalid string.
355 IPAddress.Parse (address);
358 string[] h_aliases, h_addrlist;
364 java.net.InetAddress[] iaArr =
365 java.net.InetAddress.getAllByName(address);
366 if (iaArr != null && iaArr.Length > 0)
367 h_name = iaArr[0].getHostName();
368 if (iaArr != null && iaArr.Length > 0)
370 h_addrlist = new String[iaArr.Length];
371 for (int i = 0; i < h_addrlist.Length; i++)
372 h_addrlist[i] = iaArr[i].getHostAddress();
374 } catch (java.net.UnknownHostException jUHE) {
375 throw new SocketException((int)SocketError.HostNotFound, jUHE.Message);
378 bool ret = GetHostByAddr_internal(address, out h_name, out h_aliases, out h_addrlist);
380 throw new SocketException(11001);
382 return (hostent_to_IPHostEntry (h_name, h_aliases, h_addrlist));
386 public static IPHostEntry GetHostEntry (string hostNameOrAddress)
388 if (hostNameOrAddress == null)
389 throw new ArgumentNullException ("hostNameOrAddress");
390 if (hostNameOrAddress == "0.0.0.0" || hostNameOrAddress == "::0")
391 throw new ArgumentException ("Addresses 0.0.0.0 (IPv4) " +
392 "and ::0 (IPv6) are unspecified addresses. You " +
393 "cannot use them as target address.",
394 "hostNameOrAddress");
397 if (hostNameOrAddress.Length > 0 && IPAddress.TryParse (hostNameOrAddress, out addr))
398 return GetHostEntry (addr);
400 return GetHostByName (hostNameOrAddress);
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 (hostName == null)
433 throw new ArgumentNullException ("hostName");
435 if (hostName.Length == 0)
436 hostName = "localhost";
438 java.net.InetAddress[] iaArr = java.net.InetAddress.getAllByName(hostName);
439 IPHostEntry host = new IPHostEntry();
440 if (iaArr != null && iaArr.Length > 0)
442 host.HostName = iaArr[0].getHostName();
443 IPAddress[] ipArr = new IPAddress[iaArr.Length];
444 for (int i = 0; i < iaArr.Length; i++)
445 ipArr[i] = IPAddress.Parse(iaArr[i].getHostAddress());
447 host.AddressList = ipArr;
450 } catch (java.net.UnknownHostException jUHE) {
451 throw new SocketException((int)SocketError.HostNotFound, jUHE.Message);
455 string[] h_aliases, h_addrlist;
457 bool ret = GetHostByName_internal(hostName, out h_name, out h_aliases, out h_addrlist);
459 throw new SocketException(11001);
461 return(hostent_to_IPHostEntry(h_name, h_aliases, h_addrlist));
465 public static string GetHostName ()
468 return java.net.InetAddress.getLocalHost ().getHostName ();
472 bool ret = GetHostName_internal(out hostName);
475 throw new SocketException(11001);
481 [Obsolete ("Use GetHostEntry instead")]
482 public static IPHostEntry Resolve(string hostName)
484 if (hostName == null)
485 throw new ArgumentNullException ("hostName");
487 IPHostEntry ret = null;
490 ret = GetHostByAddress(hostName);
495 ret = GetHostByName(hostName);
501 public static Task<IPAddress[]> GetHostAddressesAsync (string hostNameOrAddress)
503 return Task<IPAddress[]>.Factory.FromAsync (BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
506 public static Task<IPHostEntry> GetHostEntryAsync (IPAddress address)
508 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, address, null);
511 public static Task<IPHostEntry> GetHostEntryAsync (string hostNameOrAddress)
513 return Task<IPHostEntry>.Factory.FromAsync (BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);