mscorlib(4.0.0.0) API with additions
Dns.cs
1 using System.Collections;
3 using System.Net.Sockets;
6 using System.Text;
7 using System.Threading;
9 
10 namespace System.Net
11 {
13  public static class Dns
14  {
15  private class ResolveAsyncResult : ContextAwareResult
16  {
17  internal readonly string hostName;
18 
19  internal bool includeIPv6;
20 
21  internal IPAddress address;
22 
23  internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack)
24  : base(myObject, myState, myCallBack)
25  {
26  this.hostName = hostName;
27  this.includeIPv6 = includeIPv6;
28  }
29 
30  internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack)
31  : base(myObject, myState, myCallBack)
32  {
33  this.includeIPv6 = includeIPv6;
34  this.address = address;
35  }
36  }
37 
38  private const int HostNameBufferLength = 256;
39 
40  private static DnsPermission s_DnsPermission = new DnsPermission(PermissionState.Unrestricted);
41 
42  private const int MaxHostName = 255;
43 
44  private static WaitCallback resolveCallback = ResolveCallback;
45 
46  private static IPHostEntry NativeToHostEntry(IntPtr nativePointer)
47  {
48  hostent hostent = (hostent)Marshal.PtrToStructure(nativePointer, typeof(hostent));
49  IPHostEntry iPHostEntry = new IPHostEntry();
50  if (hostent.h_name != IntPtr.Zero)
51  {
52  iPHostEntry.HostName = Marshal.PtrToStringAnsi(hostent.h_name);
53  }
54  ArrayList arrayList = new ArrayList();
55  IntPtr intPtr = hostent.h_addr_list;
56  nativePointer = Marshal.ReadIntPtr(intPtr);
57  while (nativePointer != IntPtr.Zero)
58  {
59  int newAddress = Marshal.ReadInt32(nativePointer);
60  arrayList.Add(new IPAddress(newAddress));
61  intPtr = IntPtrHelper.Add(intPtr, IntPtr.Size);
62  nativePointer = Marshal.ReadIntPtr(intPtr);
63  }
64  iPHostEntry.AddressList = new IPAddress[arrayList.Count];
65  arrayList.CopyTo(iPHostEntry.AddressList, 0);
66  arrayList.Clear();
67  intPtr = hostent.h_aliases;
68  nativePointer = Marshal.ReadIntPtr(intPtr);
69  while (nativePointer != IntPtr.Zero)
70  {
71  string value = Marshal.PtrToStringAnsi(nativePointer);
72  arrayList.Add(value);
73  intPtr = IntPtrHelper.Add(intPtr, IntPtr.Size);
74  nativePointer = Marshal.ReadIntPtr(intPtr);
75  }
76  iPHostEntry.Aliases = new string[arrayList.Count];
77  arrayList.CopyTo(iPHostEntry.Aliases, 0);
78  return iPHostEntry;
79  }
80 
88  [Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
89  public static IPHostEntry GetHostByName(string hostName)
90  {
91  if (hostName == null)
92  {
93  throw new ArgumentNullException("hostName");
94  }
95  s_DnsPermission.Demand();
96  if (IPAddress.TryParse(hostName, out IPAddress address))
97  {
98  return GetUnresolveAnswer(address);
99  }
100  return InternalGetHostByName(hostName, includeIPv6: false);
101  }
102 
103  internal static IPHostEntry InternalGetHostByName(string hostName)
104  {
105  return InternalGetHostByName(hostName, includeIPv6: true);
106  }
107 
108  internal static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6)
109  {
110  if (Logging.On)
111  {
112  Logging.Enter(Logging.Sockets, "DNS", "GetHostByName", hostName);
113  }
114  IPHostEntry iPHostEntry = null;
115  if (hostName.Length > 255 || (hostName.Length == 255 && hostName[254] != '.'))
116  {
117  throw new ArgumentOutOfRangeException("hostName", SR.GetString("net_toolong", "hostName", 255.ToString(NumberFormatInfo.CurrentInfo)));
118  }
119  if (Socket.LegacySupportsIPv6 | includeIPv6)
120  {
121  iPHostEntry = GetAddrInfo(hostName);
122  }
123  else
124  {
125  IntPtr intPtr = UnsafeNclNativeMethods.OSSOCK.gethostbyname(hostName);
126  if (intPtr == IntPtr.Zero)
127  {
128  SocketException ex = new SocketException();
129  if (IPAddress.TryParse(hostName, out IPAddress address))
130  {
131  iPHostEntry = GetUnresolveAnswer(address);
132  if (Logging.On)
133  {
134  Logging.Exit(Logging.Sockets, "DNS", "GetHostByName", iPHostEntry);
135  }
136  return iPHostEntry;
137  }
138  throw ex;
139  }
140  iPHostEntry = NativeToHostEntry(intPtr);
141  }
142  if (Logging.On)
143  {
144  Logging.Exit(Logging.Sockets, "DNS", "GetHostByName", iPHostEntry);
145  }
146  return iPHostEntry;
147  }
148 
157  [Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
158  public static IPHostEntry GetHostByAddress(string address)
159  {
160  if (Logging.On)
161  {
162  Logging.Enter(Logging.Sockets, "DNS", "GetHostByAddress", address);
163  }
164  s_DnsPermission.Demand();
165  if (address == null)
166  {
167  throw new ArgumentNullException("address");
168  }
169  IPHostEntry iPHostEntry = InternalGetHostByAddress(IPAddress.Parse(address), includeIPv6: false);
170  if (Logging.On)
171  {
172  Logging.Exit(Logging.Sockets, "DNS", "GetHostByAddress", iPHostEntry);
173  }
174  return iPHostEntry;
175  }
176 
183  [Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
184  public static IPHostEntry GetHostByAddress(IPAddress address)
185  {
186  if (Logging.On)
187  {
188  Logging.Enter(Logging.Sockets, "DNS", "GetHostByAddress", "");
189  }
190  s_DnsPermission.Demand();
191  if (address == null)
192  {
193  throw new ArgumentNullException("address");
194  }
195  IPHostEntry iPHostEntry = InternalGetHostByAddress(address, includeIPv6: false);
196  if (Logging.On)
197  {
198  Logging.Exit(Logging.Sockets, "DNS", "GetHostByAddress", iPHostEntry);
199  }
200  return iPHostEntry;
201  }
202 
203  internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
204  {
205  SocketError errorCode = SocketError.Success;
206  Exception ex = null;
207  if (Socket.LegacySupportsIPv6 | includeIPv6)
208  {
209  string name = TryGetNameInfo(address, out errorCode);
210  if (errorCode == SocketError.Success)
211  {
212  errorCode = TryGetAddrInfo(name, out IPHostEntry hostinfo);
213  if (errorCode == SocketError.Success)
214  {
215  return hostinfo;
216  }
217  if (Logging.On)
218  {
219  Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", new SocketException(errorCode));
220  }
221  return hostinfo;
222  }
223  ex = new SocketException(errorCode);
224  }
225  else
226  {
227  if (address.AddressFamily == AddressFamily.InterNetworkV6)
228  {
229  throw new SocketException(SocketError.ProtocolNotSupported);
230  }
231  int addr = (int)address.m_Address;
232  IntPtr intPtr = UnsafeNclNativeMethods.OSSOCK.gethostbyaddr(ref addr, Marshal.SizeOf(typeof(int)), ProtocolFamily.InterNetwork);
233  if (intPtr != IntPtr.Zero)
234  {
235  return NativeToHostEntry(intPtr);
236  }
237  ex = new SocketException();
238  }
239  if (Logging.On)
240  {
241  Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", ex);
242  }
243  throw ex;
244  }
245 
249  public static string GetHostName()
250  {
251  s_DnsPermission.Demand();
252  Socket.InitializeSockets();
253  StringBuilder stringBuilder = new StringBuilder(256);
254  if (UnsafeNclNativeMethods.OSSOCK.gethostname(stringBuilder, 256) != 0)
255  {
256  throw new SocketException();
257  }
258  return stringBuilder.ToString();
259  }
260 
268  [Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
269  public static IPHostEntry Resolve(string hostName)
270  {
271  if (Logging.On)
272  {
273  Logging.Enter(Logging.Sockets, "DNS", "Resolve", hostName);
274  }
275  s_DnsPermission.Demand();
276  if (hostName == null)
277  {
278  throw new ArgumentNullException("hostName");
279  }
280  IPHostEntry iPHostEntry;
281  if (IPAddress.TryParse(hostName, out IPAddress address) && (address.AddressFamily != AddressFamily.InterNetworkV6 || Socket.LegacySupportsIPv6))
282  {
283  try
284  {
285  iPHostEntry = InternalGetHostByAddress(address, includeIPv6: false);
286  }
287  catch (SocketException ex)
288  {
289  if (Logging.On)
290  {
291  Logging.PrintWarning(Logging.Sockets, "DNS", "DNS.Resolve", ex.Message);
292  }
293  iPHostEntry = GetUnresolveAnswer(address);
294  }
295  }
296  else
297  {
298  iPHostEntry = InternalGetHostByName(hostName, includeIPv6: false);
299  }
300  if (Logging.On)
301  {
302  Logging.Exit(Logging.Sockets, "DNS", "Resolve", iPHostEntry);
303  }
304  return iPHostEntry;
305  }
306 
307  private static IPHostEntry GetUnresolveAnswer(IPAddress address)
308  {
309  IPHostEntry iPHostEntry = new IPHostEntry();
310  iPHostEntry.HostName = address.ToString();
311  iPHostEntry.Aliases = new string[0];
312  iPHostEntry.AddressList = new IPAddress[1]
313  {
314  address
315  };
316  return iPHostEntry;
317  }
318 
319  internal static bool TryInternalResolve(string hostName, out IPHostEntry result)
320  {
321  if (Logging.On)
322  {
323  Logging.Enter(Logging.Sockets, "DNS", "TryInternalResolve", hostName);
324  }
325  if (string.IsNullOrEmpty(hostName) || hostName.Length > 255)
326  {
327  result = null;
328  return false;
329  }
330  if (IPAddress.TryParse(hostName, out IPAddress address))
331  {
332  result = GetUnresolveAnswer(address);
333  return true;
334  }
335  if (TryGetAddrInfo(hostName, AddressInfoHints.AI_CANONNAME, out IPHostEntry hostinfo) != 0)
336  {
337  result = null;
338  return false;
339  }
340  result = hostinfo;
341  if (!ComNetOS.IsWin7Sp1orLater)
342  {
343  return true;
344  }
345  if (CompareHosts(hostName, hostinfo.HostName))
346  {
347  return true;
348  }
349  if (TryGetAddrInfo(hostName, AddressInfoHints.AI_FQDN, out IPHostEntry hostinfo2) != 0)
350  {
351  return true;
352  }
353  if (CompareHosts(hostinfo.HostName, hostinfo2.HostName))
354  {
355  return true;
356  }
357  hostinfo.isTrustedHost = false;
358  return true;
359  }
360 
361  private static bool CompareHosts(string host1, string host2)
362  {
363  if (TryNormalizeHost(host1, out string result) && TryNormalizeHost(host2, out string result2))
364  {
365  return result.Equals(result2, StringComparison.OrdinalIgnoreCase);
366  }
367  return host1.Equals(host2, StringComparison.OrdinalIgnoreCase);
368  }
369 
370  private static bool TryNormalizeHost(string host, out string result)
371  {
372  if (Uri.TryCreate(Uri.UriSchemeHttp + Uri.SchemeDelimiter + host, UriKind.Absolute, out Uri result2))
373  {
374  result = result2.GetComponents(UriComponents.NormalizedHost, UriFormat.SafeUnescaped);
375  return true;
376  }
377  result = null;
378  return false;
379  }
380 
381  private static void ResolveCallback(object context)
382  {
383  ResolveAsyncResult resolveAsyncResult = (ResolveAsyncResult)context;
384  IPHostEntry result;
385  try
386  {
387  result = ((resolveAsyncResult.address == null) ? InternalGetHostByName(resolveAsyncResult.hostName, resolveAsyncResult.includeIPv6) : InternalGetHostByAddress(resolveAsyncResult.address, resolveAsyncResult.includeIPv6));
388  }
389  catch (Exception ex)
390  {
391  if (ex is OutOfMemoryException || ex is ThreadAbortException || ex is StackOverflowException)
392  {
393  throw;
394  }
395  resolveAsyncResult.InvokeCallback(ex);
396  return;
397  }
398  resolveAsyncResult.InvokeCallback(result);
399  }
400 
401  private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool flowContext, bool includeIPv6, bool throwOnIPAny, AsyncCallback requestCallback, object state)
402  {
403  s_DnsPermission.Demand();
404  if (hostName == null)
405  {
406  throw new ArgumentNullException("hostName");
407  }
408  ResolveAsyncResult resolveAsyncResult;
409  if (IPAddress.TryParse(hostName, out IPAddress address))
410  {
411  if (throwOnIPAny && (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)))
412  {
413  throw new ArgumentException(SR.GetString("net_invalid_ip_addr"), "hostNameOrAddress");
414  }
415  resolveAsyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
416  if (justReturnParsedIp)
417  {
418  IPHostEntry unresolveAnswer = GetUnresolveAnswer(address);
419  resolveAsyncResult.StartPostingAsyncOp(lockCapture: false);
420  resolveAsyncResult.InvokeCallback(unresolveAnswer);
421  resolveAsyncResult.FinishPostingAsyncOp();
422  return resolveAsyncResult;
423  }
424  }
425  else
426  {
427  resolveAsyncResult = new ResolveAsyncResult(hostName, null, includeIPv6, state, requestCallback);
428  }
429  if (flowContext)
430  {
431  resolveAsyncResult.StartPostingAsyncOp(lockCapture: false);
432  }
433  ThreadPool.UnsafeQueueUserWorkItem(resolveCallback, resolveAsyncResult);
434  resolveAsyncResult.FinishPostingAsyncOp();
435  return resolveAsyncResult;
436  }
437 
438  private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state)
439  {
440  s_DnsPermission.Demand();
441  if (address == null)
442  {
443  throw new ArgumentNullException("address");
444  }
445  if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
446  {
447  throw new ArgumentException(SR.GetString("net_invalid_ip_addr"), "address");
448  }
449  ResolveAsyncResult resolveAsyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback);
450  if (flowContext)
451  {
452  resolveAsyncResult.StartPostingAsyncOp(lockCapture: false);
453  }
454  ThreadPool.UnsafeQueueUserWorkItem(resolveCallback, resolveAsyncResult);
455  resolveAsyncResult.FinishPostingAsyncOp();
456  return resolveAsyncResult;
457  }
458 
459  private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult)
460  {
461  if (asyncResult == null)
462  {
463  throw new ArgumentNullException("asyncResult");
464  }
465  ResolveAsyncResult resolveAsyncResult = asyncResult as ResolveAsyncResult;
466  if (resolveAsyncResult == null)
467  {
468  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
469  }
470  if (resolveAsyncResult.EndCalled)
471  {
472  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndResolve"));
473  }
474  resolveAsyncResult.InternalWaitForCompletion();
475  resolveAsyncResult.EndCalled = true;
476  Exception ex = resolveAsyncResult.Result as Exception;
477  if (ex != null)
478  {
479  throw ex;
480  }
481  return (IPHostEntry)resolveAsyncResult.Result;
482  }
483 
492  [Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
493  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
494  public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject)
495  {
496  if (Logging.On)
497  {
498  Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostByName", hostName);
499  }
500  IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, justReturnParsedIp: true, flowContext: true, includeIPv6: false, throwOnIPAny: false, requestCallback, stateObject);
501  if (Logging.On)
502  {
503  Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostByName", asyncResult);
504  }
505  return asyncResult;
506  }
507 
513  [Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
514  public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
515  {
516  if (Logging.On)
517  {
518  Logging.Enter(Logging.Sockets, "DNS", "EndGetHostByName", asyncResult);
519  }
520  IPHostEntry iPHostEntry = HostResolutionEndHelper(asyncResult);
521  if (Logging.On)
522  {
523  Logging.Exit(Logging.Sockets, "DNS", "EndGetHostByName", iPHostEntry);
524  }
525  return iPHostEntry;
526  }
527 
535  public static IPHostEntry GetHostEntry(string hostNameOrAddress)
536  {
537  if (Logging.On)
538  {
539  Logging.Enter(Logging.Sockets, "DNS", "GetHostEntry", hostNameOrAddress);
540  }
541  s_DnsPermission.Demand();
542  if (hostNameOrAddress == null)
543  {
544  throw new ArgumentNullException("hostNameOrAddress");
545  }
546  IPHostEntry iPHostEntry;
547  if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
548  {
549  if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
550  {
551  throw new ArgumentException(SR.GetString("net_invalid_ip_addr"), "hostNameOrAddress");
552  }
553  iPHostEntry = InternalGetHostByAddress(address, includeIPv6: true);
554  }
555  else
556  {
557  iPHostEntry = InternalGetHostByName(hostNameOrAddress, includeIPv6: true);
558  }
559  if (Logging.On)
560  {
561  Logging.Exit(Logging.Sockets, "DNS", "GetHostEntry", iPHostEntry);
562  }
563  return iPHostEntry;
564  }
565 
574  public static IPHostEntry GetHostEntry(IPAddress address)
575  {
576  if (Logging.On)
577  {
578  Logging.Enter(Logging.Sockets, "DNS", "GetHostEntry", "");
579  }
580  s_DnsPermission.Demand();
581  if (address == null)
582  {
583  throw new ArgumentNullException("address");
584  }
585  if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
586  {
587  throw new ArgumentException(SR.GetString("net_invalid_ip_addr"), "address");
588  }
589  IPHostEntry iPHostEntry = InternalGetHostByAddress(address, includeIPv6: true);
590  if (Logging.On)
591  {
592  Logging.Exit(Logging.Sockets, "DNS", "GetHostEntry", iPHostEntry);
593  }
594  return iPHostEntry;
595  }
596 
606  public static IPAddress[] GetHostAddresses(string hostNameOrAddress)
607  {
608  if (Logging.On)
609  {
610  Logging.Enter(Logging.Sockets, "DNS", "GetHostAddresses", hostNameOrAddress);
611  }
612  s_DnsPermission.Demand();
613  if (hostNameOrAddress == null)
614  {
615  throw new ArgumentNullException("hostNameOrAddress");
616  }
617  IPAddress[] array;
618  if (IPAddress.TryParse(hostNameOrAddress, out IPAddress address))
619  {
620  if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
621  {
622  throw new ArgumentException(SR.GetString("net_invalid_ip_addr"), "hostNameOrAddress");
623  }
624  array = new IPAddress[1]
625  {
626  address
627  };
628  }
629  else
630  {
631  array = InternalGetHostByName(hostNameOrAddress, includeIPv6: true).AddressList;
632  }
633  if (Logging.On)
634  {
635  Logging.Exit(Logging.Sockets, "DNS", "GetHostAddresses", array);
636  }
637  return array;
638  }
639 
651  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
652  public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
653  {
654  if (Logging.On)
655  {
656  Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostEntry", hostNameOrAddress);
657  }
658  IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, justReturnParsedIp: false, flowContext: true, includeIPv6: true, throwOnIPAny: true, requestCallback, stateObject);
659  if (Logging.On)
660  {
661  Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostEntry", asyncResult);
662  }
663  return asyncResult;
664  }
665 
676  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
677  public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject)
678  {
679  if (Logging.On)
680  {
681  Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostEntry", address);
682  }
683  IAsyncResult asyncResult = HostResolutionBeginHelper(address, flowContext: true, includeIPv6: true, requestCallback, stateObject);
684  if (Logging.On)
685  {
686  Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostEntry", asyncResult);
687  }
688  return asyncResult;
689  }
690 
696  public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
697  {
698  if (Logging.On)
699  {
700  Logging.Enter(Logging.Sockets, "DNS", "EndGetHostEntry", asyncResult);
701  }
702  IPHostEntry iPHostEntry = HostResolutionEndHelper(asyncResult);
703  if (Logging.On)
704  {
705  Logging.Exit(Logging.Sockets, "DNS", "EndGetHostEntry", iPHostEntry);
706  }
707  return iPHostEntry;
708  }
709 
721  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
722  public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state)
723  {
724  if (Logging.On)
725  {
726  Logging.Enter(Logging.Sockets, "DNS", "BeginGetHostAddresses", hostNameOrAddress);
727  }
728  IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, justReturnParsedIp: true, flowContext: true, includeIPv6: true, throwOnIPAny: true, requestCallback, state);
729  if (Logging.On)
730  {
731  Logging.Exit(Logging.Sockets, "DNS", "BeginGetHostAddresses", asyncResult);
732  }
733  return asyncResult;
734  }
735 
739  public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult)
740  {
741  if (Logging.On)
742  {
743  Logging.Enter(Logging.Sockets, "DNS", "EndGetHostAddresses", asyncResult);
744  }
745  IPHostEntry iPHostEntry = HostResolutionEndHelper(asyncResult);
746  if (Logging.On)
747  {
748  Logging.Exit(Logging.Sockets, "DNS", "EndGetHostAddresses", iPHostEntry);
749  }
750  return iPHostEntry.AddressList;
751  }
752 
753  internal static IAsyncResult UnsafeBeginGetHostAddresses(string hostName, AsyncCallback requestCallback, object state)
754  {
755  if (Logging.On)
756  {
757  Logging.Enter(Logging.Sockets, "DNS", "UnsafeBeginGetHostAddresses", hostName);
758  }
759  IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, justReturnParsedIp: true, flowContext: false, includeIPv6: true, throwOnIPAny: true, requestCallback, state);
760  if (Logging.On)
761  {
762  Logging.Exit(Logging.Sockets, "DNS", "UnsafeBeginGetHostAddresses", asyncResult);
763  }
764  return asyncResult;
765  }
766 
775  [Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
776  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
777  public static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject)
778  {
779  if (Logging.On)
780  {
781  Logging.Enter(Logging.Sockets, "DNS", "BeginResolve", hostName);
782  }
783  IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, justReturnParsedIp: false, flowContext: true, includeIPv6: false, throwOnIPAny: false, requestCallback, stateObject);
784  if (Logging.On)
785  {
786  Logging.Exit(Logging.Sockets, "DNS", "BeginResolve", asyncResult);
787  }
788  return asyncResult;
789  }
790 
796  [Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")]
797  public static IPHostEntry EndResolve(IAsyncResult asyncResult)
798  {
799  if (Logging.On)
800  {
801  Logging.Enter(Logging.Sockets, "DNS", "EndResolve", asyncResult);
802  }
803  IPHostEntry iPHostEntry;
804  try
805  {
806  iPHostEntry = HostResolutionEndHelper(asyncResult);
807  }
808  catch (SocketException ex)
809  {
810  IPAddress address = ((ResolveAsyncResult)asyncResult).address;
811  if (address == null)
812  {
813  throw;
814  }
815  if (Logging.On)
816  {
817  Logging.PrintWarning(Logging.Sockets, "DNS", "DNS.EndResolve", ex.Message);
818  }
819  iPHostEntry = GetUnresolveAnswer(address);
820  }
821  if (Logging.On)
822  {
823  Logging.Exit(Logging.Sockets, "DNS", "EndResolve", iPHostEntry);
824  }
825  return iPHostEntry;
826  }
827 
837  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
838  public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress)
839  {
840  return Task<IPAddress[]>.Factory.FromAsync(BeginGetHostAddresses, EndGetHostAddresses, hostNameOrAddress, null);
841  }
842 
851  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
853  {
854  return Task<IPHostEntry>.Factory.FromAsync(BeginGetHostEntry, EndGetHostEntry, address, null);
855  }
856 
864  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
865  public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress)
866  {
867  return Task<IPHostEntry>.Factory.FromAsync(BeginGetHostEntry, EndGetHostEntry, hostNameOrAddress, null);
868  }
869 
870  private static IPHostEntry GetAddrInfo(string name)
871  {
872  IPHostEntry hostinfo;
873  SocketError socketError = TryGetAddrInfo(name, out hostinfo);
874  if (socketError != 0)
875  {
876  throw new SocketException(socketError);
877  }
878  return hostinfo;
879  }
880 
881  private static SocketError TryGetAddrInfo(string name, out IPHostEntry hostinfo)
882  {
883  return TryGetAddrInfo(name, AddressInfoHints.AI_CANONNAME, out hostinfo);
884  }
885 
886  private unsafe static SocketError TryGetAddrInfo(string name, AddressInfoHints flags, out IPHostEntry hostinfo)
887  {
888  SafeFreeAddrInfo outAddrInfo = null;
889  ArrayList arrayList = new ArrayList();
890  string text = null;
891  AddressInfo hints = default(AddressInfo);
892  hints.ai_flags = flags;
893  hints.ai_family = AddressFamily.Unspecified;
894  try
895  {
896  SocketError addrInfo = (SocketError)SafeFreeAddrInfo.GetAddrInfo(name, null, ref hints, out outAddrInfo);
897  if (addrInfo != 0)
898  {
899  hostinfo = new IPHostEntry();
900  hostinfo.HostName = name;
901  hostinfo.Aliases = new string[0];
902  hostinfo.AddressList = new IPAddress[0];
903  return addrInfo;
904  }
905  for (AddressInfo* ptr = (AddressInfo*)(void*)outAddrInfo.DangerousGetHandle(); ptr != null; ptr = ptr->ai_next)
906  {
907  if (text == null && ptr->ai_canonname != null)
908  {
909  text = Marshal.PtrToStringUni((IntPtr)(void*)ptr->ai_canonname);
910  }
911  if (ptr->ai_family == AddressFamily.InterNetwork || (ptr->ai_family == AddressFamily.InterNetworkV6 && Socket.OSSupportsIPv6))
912  {
913  SocketAddress socketAddress = new SocketAddress(ptr->ai_family, ptr->ai_addrlen);
914  for (int i = 0; i < ptr->ai_addrlen; i++)
915  {
916  socketAddress.m_Buffer[i] = ptr->ai_addr[i];
917  }
918  if (ptr->ai_family == AddressFamily.InterNetwork)
919  {
920  arrayList.Add(((IPEndPoint)IPEndPoint.Any.Create(socketAddress)).Address);
921  }
922  else
923  {
924  arrayList.Add(((IPEndPoint)IPEndPoint.IPv6Any.Create(socketAddress)).Address);
925  }
926  }
927  }
928  }
929  finally
930  {
931  outAddrInfo?.Close();
932  }
933  hostinfo = new IPHostEntry();
934  hostinfo.HostName = ((text != null) ? text : name);
935  hostinfo.Aliases = new string[0];
936  hostinfo.AddressList = new IPAddress[arrayList.Count];
937  arrayList.CopyTo(hostinfo.AddressList);
938  return SocketError.Success;
939  }
940 
941  internal static string TryGetNameInfo(IPAddress addr, out SocketError errorCode)
942  {
943  SocketAddress socketAddress = new IPEndPoint(addr, 0).Serialize();
944  StringBuilder stringBuilder = new StringBuilder(1025);
945  int flags = 4;
946  Socket.InitializeSockets();
947  errorCode = UnsafeNclNativeMethods.OSSOCK.GetNameInfoW(socketAddress.m_Buffer, socketAddress.m_Size, stringBuilder, stringBuilder.Capacity, null, 0, flags);
948  if (errorCode != 0)
949  {
950  return null;
951  }
952  return stringBuilder.ToString();
953  }
954  }
955 }
UriKind
Defines the kinds of T:System.Uris for the M:System.Uri.IsWellFormedUriString(System....
Definition: UriKind.cs:5
static new TaskFactory< TResult > Factory
Provides access to factory methods for creating and configuring T:System.Threading....
Definition: Task.cs:75
static IPHostEntry GetHostEntry(IPAddress address)
Resolves an IP address to an T:System.Net.IPHostEntry instance.
Definition: Dns.cs:574
static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state)
Asynchronously returns the Internet Protocol (IP) addresses for the specified host.
Definition: Dns.cs:722
static IPHostEntry GetHostEntry(string hostNameOrAddress)
Resolves a host name or IP address to an T:System.Net.IPHostEntry instance.
Definition: Dns.cs:535
static int ReadInt32([In] [MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
Reads a 32-bit signed integer at a given offset from unmanaged memory.
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
static Task< IPHostEntry > GetHostEntryAsync(IPAddress address)
Resolves an IP address to an T:System.Net.IPHostEntry instance as an asynchronous operation.
Definition: Dns.cs:852
unsafe override string ToString()
Converts the value of this instance to a T:System.String.
override string Message
Gets the error message that is associated with this exception.
static Task< IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress)
Returns the Internet Protocol (IP) addresses for the specified host as an asynchronous operation.
Definition: Dns.cs:838
StringComparison
Specifies the culture, case, and sort rules to be used by certain overloads of the M:System....
static IPHostEntry Resolve(string hostName)
Resolves a DNS host name or IP address to an T:System.Net.IPHostEntry instance.
Definition: Dns.cs:269
static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject)
Begins an asynchronous request for T:System.Net.IPHostEntry information about the specified DNS host ...
Definition: Dns.cs:494
static readonly IPAddress Any
Provides an IP address that indicates that the server must listen for client activity on all network ...
Definition: IPAddress.cs:14
virtual int Count
Gets the number of elements actually contained in the T:System.Collections.ArrayList.
Definition: ArrayList.cs:2255
static Task< IPHostEntry > GetHostEntryAsync(string hostNameOrAddress)
Resolves a host name or IP address to an T:System.Net.IPHostEntry instance as an asynchronous operati...
Definition: Dns.cs:865
Definition: __Canon.cs:3
static int SizeOf(object structure)
Returns the unmanaged size of an object in bytes.
Definition: Marshal.cs:159
delegate void AsyncCallback(IAsyncResult ar)
References a method to be called when a corresponding asynchronous operation completes.
static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object state)
Queues the specified delegate to the thread pool, but does not propagate the calling stack to the wor...
Definition: ThreadPool.cs:312
Implements the Berkeley sockets interface.
Definition: Socket.cs:16
unsafe override string ToString()
Converts an Internet address to its standard notation.
Definition: IPAddress.cs:503
virtual void Clear()
Removes all elements from the T:System.Collections.ArrayList.
Definition: ArrayList.cs:2461
static IPAddress Parse(string ipString)
Converts an IP address string to an T:System.Net.IPAddress instance.
Definition: IPAddress.cs:371
static bool TryParse(string ipString, out IPAddress address)
Determines whether a string is a valid IP address.
Definition: IPAddress.cs:357
static NumberFormatInfo CurrentInfo
Gets a read-only T:System.Globalization.NumberFormatInfo that formats values based on the current cul...
Provides a container class for Internet host address information.
Definition: IPHostEntry.cs:4
The exception that is thrown when a socket error occurs.
AddressFamily AddressFamily
Gets the address family of the IP address.
Definition: IPAddress.cs:111
UriComponents
Specifies the parts of a T:System.Uri.
Definition: UriComponents.cs:6
static IPAddress [] GetHostAddresses(string hostNameOrAddress)
Returns the Internet Protocol (IP) addresses for the specified host.
Definition: Dns.cs:606
Provides an Internet Protocol (IP) address.
Definition: IPAddress.cs:10
SecurityAction
Specifies the security actions that can be performed using declarative security.
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
static IPHostEntry EndResolve(IAsyncResult asyncResult)
Ends an asynchronous request for DNS information.
Definition: Dns.cs:797
static readonly IPAddress IPv6Any
The M:System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method uses the F:System....
Definition: IPAddress.cs:37
static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult)
Ends an asynchronous request for DNS information.
Definition: Dns.cs:696
AddressFamily
Specifies the addressing scheme that an instance of the T:System.Net.Sockets.Socket class can use.
Definition: AddressFamily.cs:5
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
static IPHostEntry GetHostByName(string hostName)
Gets the DNS information for the specified DNS host name.
Definition: Dns.cs:89
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Definition: Marshal.cs:15
string HostName
Gets or sets the DNS name of the host.
Definition: IPHostEntry.cs:17
Controls rights to access Domain Name System (DNS) servers on the network.
Definition: DnsPermission.cs:8
virtual void CopyTo(Array array)
Copies the entire T:System.Collections.ArrayList to a compatible one-dimensional T:System....
Definition: ArrayList.cs:2516
static IPAddress [] EndGetHostAddresses(IAsyncResult asyncResult)
Ends an asynchronous request for DNS information.
Definition: Dns.cs:739
IPAddress [] AddressList
Gets or sets a list of IP addresses that are associated with a host.
Definition: IPHostEntry.cs:45
static string GetHostName()
Gets the host name of the local computer.
Definition: Dns.cs:249
Represents a mutable string of characters. This class cannot be inherited.To browse the ....
virtual int Add(object value)
Adds an object to the end of the T:System.Collections.ArrayList.
Definition: ArrayList.cs:2381
static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject)
Asynchronously resolves an IP address to an T:System.Net.IPHostEntry instance.
Definition: Dns.cs:677
The exception that is thrown when one of the arguments provided to a method is not valid.
void Demand()
Forces a T:System.Security.SecurityException at run time if all callers higher in the call stack have...
ProtocolFamily
Specifies the type of protocol that an instance of the T:System.Net.Sockets.Socket class can use.
static int Size
Gets the size of this instance.
Definition: IntPtr.cs:27
UriFormat
Controls how URI information is escaped.
Definition: UriFormat.cs:5
static unsafe string PtrToStringUni(IntPtr ptr, int len)
Allocates a managed T:System.String and copies a specified number of characters from an unmanaged Uni...
Definition: Marshal.cs:103
static IntPtr Add(IntPtr pointer, int offset)
Adds an offset to the value of a pointer.
Definition: IntPtr.cs:271
int Capacity
Gets or sets the maximum number of characters that can be contained in the memory allocated by the cu...
static void PtrToStructure(IntPtr ptr, object structure)
Marshals data from an unmanaged block of memory to a managed object.
Definition: Marshal.cs:1198
PermissionState
Specifies whether a permission should have all or no access to resources at creation.
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
string [] Aliases
Gets or sets a list of aliases that are associated with a host.
Definition: IPHostEntry.cs:31
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
Definition: IntPtr.cs:20
static IPHostEntry EndGetHostByName(IAsyncResult asyncResult)
Ends an asynchronous request for DNS information.
Definition: Dns.cs:514
Provides simple domain name resolution functionality.
Definition: Dns.cs:13
static bool OSSupportsIPv6
Indicates whether the underlying operating system and network adaptors support Internet Protocol vers...
Definition: Socket.cs:268
static IPHostEntry GetHostByAddress(string address)
Creates an T:System.Net.IPHostEntry instance from an IP address.
Definition: Dns.cs:158
delegate void WaitCallback(object state)
Represents a callback method to be executed by a thread pool thread.
static unsafe string PtrToStringAnsi(IntPtr ptr)
Copies all characters up to the first null character from an unmanaged ANSI string to a managed T:Sys...
Definition: Marshal.cs:61
The exception that is thrown when a call is made to the M:System.Threading.Thread....
static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject)
Asynchronously resolves a host name or IP address to an T:System.Net.IPHostEntry instance.
Definition: Dns.cs:652
SocketError
Defines error codes for the T:System.Net.Sockets.Socket class.
Definition: SocketError.cs:5
static IPHostEntry GetHostByAddress(IPAddress address)
Creates an T:System.Net.IPHostEntry instance from the specified T:System.Net.IPAddress.
Definition: Dns.cs:184
static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject)
Begins an asynchronous request to resolve a DNS host name or IP address to an T:System....
Definition: Dns.cs:777
static IntPtr ReadIntPtr([In] [MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs)
Reads a processor native sized integer from unmanaged memory.
Definition: Marshal.cs:681
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
Definition: ThreadPool.cs:14
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
Implements the T:System.Collections.IList interface using an array whose size is dynamically increase...
Definition: ArrayList.cs:14
Provides culture-specific information for formatting and parsing numeric values.