// Record the IPs in the state object for later use. public void GetHostEntryCallback(IAsyncResult ar) { ResolveState ioContext = (ResolveState)ar.AsyncState; LookupState returnState = new LookupState(); returnState.hostName = ioContext.host; try { ioContext.IPs = Dns.EndResolve(ar); returnState.successful = true; returnState.resolvedIPs = ioContext.IPs; } catch (SocketException se) { returnState.successful = false; returnState.message = se.Message; } catch (Exception e) { returnState.successful = false; returnState.message = e.Message; } GetHostEntryFinished.Set(); ioContext.Callback.Invoke(returnState); }
public void AsyncResolve() { IAsyncResult async = Dns.BeginResolve(site1Dot, null, null); IPHostEntry entry = Dns.EndResolve(async); SubTestValidIPHostEntry(entry); CheckIPv4Address(entry, IPAddress.Parse(site1Dot)); }
public static IPEndPoint GetIPEndPoint(string __ip, int __port) { // init vars IPEndPoint ret = null; IPHostEntry ipEntry; // The IP Address Array. Holds an array of resolved Host Names. IPAddress ipAddr; if (__ip.ToLower().CompareTo("localhost") == 0 || __ip.ToLower().CompareTo("0.0.0.0") == 0) { __ip = IPHost(); } // Value of alpha characters char[] alpha = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ-".ToCharArray(); // If alpha characters exist we know we are doing a forward lookup if (__ip.IndexOfAny(alpha) == -1) { ipEntry = Dns.GetHostByName(__ip); if (ipEntry.AddressList.Length > 0) { ipAddr = ipEntry.AddressList[0]; if (__port < 0) { __port = 0; } ret = new IPEndPoint(ipAddr, __port); } } else { if (__ip.ToLower() == "any") { ret = new IPEndPoint(IPAddress.Any, __port); } else { IAsyncResult __iar = Dns.BeginResolve(__ip, null, null); __iar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(10), false); if (__iar.IsCompleted) { ipEntry = Dns.EndResolve(__iar); if (ipEntry != null) { ipAddr = ipEntry.AddressList[0]; if (__port < 0) { __port = 0; } ret = new IPEndPoint(ipAddr, __port); } } } } return(ret); }
/// <summary> /// Called when the specified hostname has been resolved. /// </summary> /// <param name="asyncResult">The result of the asynchronous operation.</param> private void OnResolved(IAsyncResult asyncResult) { try { IPHostEntry dns = Dns.EndResolve(asyncResult); base.BeginConnect(new IPEndPoint(dns.AddressList[0], RemotePort), new AsyncCallback(OnConnect), State); } catch (Exception e) { OnHandShakeComplete(e); } }
public void OnResolve(IAsyncResult result) { IPHostEntry entry = Dns.EndResolve(result); if (entry.AddressList.Length > 0) { this.Connect(new IPEndPoint(entry.AddressList[0], this.m_Server.Port)); } }
public void DnsObsoleteBeginResolve_BadIPv4String_ReturnsOnlyGivenIP() { IAsyncResult asyncObject = Dns.BeginResolve("0.0.1.1", null, null); IPHostEntry entry = Dns.EndResolve(asyncObject); Assert.Equal("0.0.1.1", entry.HostName); Assert.Equal(1, entry.AddressList.Length); Assert.Equal(IPAddress.Parse("0.0.1.1"), entry.AddressList[0]); }
public void DnsObsoleteBeginResolve_Loopback_MatchesResolve() { IAsyncResult asyncObject = Dns.BeginResolve(IPAddress.Loopback.ToString(), null, null); IPHostEntry results = Dns.EndResolve(asyncObject); IPHostEntry entry = Dns.Resolve(IPAddress.Loopback.ToString()); Assert.Equal(entry.HostName, results.HostName); Assert.Equal(entry.AddressList, results.AddressList); }
public void AsyncResolve() { IAsyncResult async = Dns.BeginResolve(site1Dot, null, null); IPHostEntry entry = Dns.EndResolve(async); SubTestValidIPHostEntry(entry); var ip = GetIPv4Address(entry); Assert.AreEqual(site1Dot, ip.ToString()); }
public void AsyncResolve() { IAsyncResult r; r = Dns.BeginResolve(site1Name, new AsyncCallback(ResolveCallback), null); IAsyncResult async = Dns.BeginResolve(site1Dot, null, null); IPHostEntry entry = Dns.EndResolve(async); SubTestValidIPHostEntry(entry); Assert.AreEqual(site1Dot, entry.AddressList [0].ToString()); }
private static void ResponseCallback(IAsyncResult Result) { try { RequestState State = (RequestState)Result.AsyncState; //非同步解析 DNS 資訊 State.host = Dns.EndResolve(Result); allDone.Set(); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void AsyncFrameworkCallbackMethod(IAsyncResult ar) { // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { IPHostEntry hostInformation = Dns.EndResolve(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } }
private void EndResolve() { if (State != ClientState.Disconnected) { try { _hostEntry = Dns.EndResolve(_currentAsyncResult); } catch (Exception e) { if (!HandleException(e)) { throw new AsyncTcpClientException(this, e); } OnResolveFailed(); return; } try { State = ClientState.Connecting; _socket = new SecureSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); if (_ssl3Enabled) { _socket.ChangeSecurityProtocol(new SecurityOptions(SecureProtocol.Ssl3)); } _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, Timeout); _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, Timeout); _endPoint = new IPEndPoint(_hostEntry.AddressList[0], _port); if (_traceProtocol) { Trace("Connecting to " + _endPoint.Address.ToString() + ':' + _endPoint.Port.ToString()); } CloseAsyncWaitHandle(); _currentAsyncResult = _socket.BeginConnect(_endPoint, null, null); InvokeAfterWait(new MethodInvoker(EndConnect), _currentAsyncResult.AsyncWaitHandle); } catch (Exception e) { if (!HandleException(e)) { throw new AsyncTcpClientException(this, e); } OnConnectFailed(); return; } } }
private void ResolveCallback(IAsyncResult ar) { Dns.EndResolve(ar); try { // can we do something bad here ? Assert.IsNotNull(Environment.GetEnvironmentVariable("USERNAME")); message = "Expected a SecurityException"; } catch (SecurityException) { message = null; reset.Set(); } catch (Exception e) { message = e.ToString(); } }
private void Resolved(IAsyncResult ar) { string buffer; IPHostEntry iphe = Dns.EndResolve(ar); // dùng lưu thông tin DNS của địa chỉ buffer = "Host name: " + iphe.HostName; // chuỗi lưu tên miền DNS results.Invoke(new Action(() => results.Items.Add(buffer))); // thêm chuỗi buffer vào list view foreach (string alias in iphe.Aliases) { buffer = "Alias: " + alias; // lưu bí danh của tên miền DNS // results.Items.Add(buffer); // results.Invoke(new Action(() => results.Items.Add(buffer))); // thêm buffer vào list view } foreach (IPAddress addrs in iphe.AddressList) { buffer = "Address: " + addrs.ToString(); // chuyển ip thành chuỗi lưu vào buffer results.Invoke(new Action(() => results.Items.Add(buffer))); // in chuỗi địa chỉ IP } }
/* Now we must show the found data. We use the keyword "string" to group the data in lines. * along with the objects of the DNS resolving */ private void Resolved(IAsyncResult ar) { string buffer; IPHostEntry iphe = Dns.EndResolve(ar); buffer = "Host name: " + iphe.HostName; results.Items.Add(buffer); foreach (string alias in iphe.Aliases) { buffer = "Alias: " + alias; results.Items.Add(buffer); } foreach (IPAddress addrs in iphe.AddressList) { buffer = "IP: " + addrs.ToString(); results.Items.Add(buffer); } }
public void AsyncResolveCallback() { var evt = new ManualResetEvent(false); Exception ex = null; Dns.BeginResolve(site1Name, new AsyncCallback((IAsyncResult ar) => { try { IPHostEntry h = Dns.EndResolve(ar); SubTestValidIPHostEntry(h); } catch (Exception e) { ex = e; } finally { evt.Set(); } }), null); Assert.IsTrue(evt.WaitOne(TimeSpan.FromSeconds(60)), "Wait"); Assert.IsNull(ex, "Exception"); }
private static void Resolved(IAsyncResult ar) { string buffer; IPHostEntry iphe = Dns.EndResolve(ar); buffer = "Host name: " + iphe.HostName; Console.WriteLine(buffer); foreach (string alias in iphe.Aliases) { buffer = "Alias: " + alias; Console.WriteLine(buffer); } for (int i = 0; i < iphe.AddressList.Length; i++) { IPAddress addrs = iphe.AddressList[i]; buffer = "Address: " + addrs.ToString(); Console.WriteLine(buffer); } }
private void EndResolvCallBack(IAsyncResult re) { string str = (string)null; PC asyncState = (PC)re.AsyncState; try { str = Dns.EndResolve(re).HostName; if (str == (string)null) { str = "noname"; } object[] objArray = new object[2]; this.resolvState = objArray; objArray[0] = (object)asyncState; this.resolvState[1] = (object)str; this.Invoke((Delegate) new DelUpdateName(this.updateTreeViewNameCallBack), this.resolvState); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static void RespCallback(IAsyncResult ar) { try { // Convert the IAsyncResult object to a RequestState object. RequestState tempRequestState = (RequestState)ar.AsyncState; // End the asynchronous request. tempRequestState.host = Dns.EndResolve(ar); allDone.Set(); } catch (ArgumentNullException e) { Console.WriteLine("ArgumentNullException caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } catch (Exception e) { Console.WriteLine("Exception caught!!!"); Console.WriteLine("Source : " + e.Source); Console.WriteLine("Message : " + e.Message); } }
public static bool Connect() { m_ServerHost = NewConfig.ServerHost; m_ServerPort = NewConfig.ServerPort; try { Debug.Try("Parsing IP ( \"{0}\" )", m_ServerHost); m_ServerIP = IPAddress.Parse(m_ServerHost); m_ServerIPEP = new IPEndPoint(m_ServerIP, m_ServerPort); Debug.EndTry("( {0} )", m_ServerIPEP); } catch { Debug.FailTry(); try { Debug.Try("Resolving"); IAsyncResult asyncResult = Dns.BeginResolve(m_ServerHost, null, null); do { Engine.DrawNow(); }while (!asyncResult.AsyncWaitHandle.WaitOne(10, false)); IPHostEntry entry = Dns.EndResolve(asyncResult); if (entry.AddressList.Length == 0) { Debug.FailTry("( AddressList is empty )"); return(false); } m_ServerIP = entry.AddressList[0]; m_ServerIPEP = new IPEndPoint(m_ServerIP, m_ServerPort); Debug.EndTry("( {0} )", m_ServerIPEP); } catch (Exception exception) { Debug.FailTry(); Debug.Error(exception); return(false); } } Flush(); Engine.ValidateHandlers(); m_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Debug.Try("Connecting to login server '{0}'", m_ServerIPEP); try { IAsyncResult result2 = m_Server.BeginConnect(m_ServerIPEP, null, null); do { Engine.DrawNow(); }while (!result2.AsyncWaitHandle.WaitOne(10, false)); m_Server.EndConnect(result2); } catch (Exception exception2) { Debug.FailTry(); Debug.Error(exception2); return(false); } Debug.EndTry(); return(true); }
private void bringname(IAsyncResult ar) { IPHostEntry ipe = Dns.EndResolve(ar); listBox1.Items.Add((string)ar.AsyncState + " " + ipe.HostName); }
public void DnsObsoleteBeginResolve_BadName_Throws() { IAsyncResult asyncObject = Dns.BeginResolve("BadName", null, null); Assert.ThrowsAny <SocketException>(() => Dns.EndResolve(asyncObject)); }
public void Deny_EndResolve() { Dns.EndResolve(null); }
void ResolveCallback(IAsyncResult ar) { IPHostEntry h = Dns.EndResolve(ar); SubTestValidIPHostEntry(h); }
/// <summary> /// This method is called by the Main static method to perform the /// DNS resolutions requested by the user demonstrating the callback /// options specified. /// </summary> /// <param name="host">An IP address or host name to resolve</param> /// <param name="methodToUse">The callback option to demonstrate</param> private void DoResolve(string host, CallbackOption methodToUse) { resultsDisplayed = false; IPHostEntry hostInformation = null; Resolver resolver = new Resolver(); switch (methodToUse) { case CallbackOption.UseInterface: { Console.WriteLine("Resolving..."); // By passing an interface that this object supports, the called // method can notify this object of the results try { resolver.Resolve(host, (IResolveCallback)this); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break; } case CallbackOption.UseSynchronousDelegate: { Console.WriteLine("Resolving..."); // By passing a delegate wrapping the HostResolved method, the // called object can notify this object of the result in a synchronous // or asynchronous manner, depending on how it is constructed. ResolveCallbackDelegate cb = new ResolveCallbackDelegate(HostResolved); resolver.Resolve(host, cb); break; } case CallbackOption.UseAsynchronousDelegateWithWait: { Console.Write("Resolving"); // By wrapping a synchronous long-running method (DNS resolution) // with a delegate, this object can call that method // asynchronously and show progress (in this case) or do other // work while it executes. In this scenario, it waits on the // result using the WaitHandle provided by IAsyncResult. ResolveDelegate synchMethod = new ResolveDelegate(resolver.Resolve); // The BeginInvoke method is supplied by the C# compiler... // The IntelliSense engine does not display this at design time. IAsyncResult ar = synchMethod.BeginInvoke(host, null, null); // Write another period for each 100ms interval of wait time. while (!ar.AsyncWaitHandle.WaitOne(100, false)) { Console.Write("."); } Console.WriteLine(); // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { // The EndInvoke method is supplied by the C# compiler... // The IntelliSense engine does not display this at design time. hostInformation = synchMethod.EndInvoke(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break; } case CallbackOption.UseAsynchronousDelegateWithCallback: { Console.WriteLine("Resolving..."); ResolveDelegate synchMethod = new ResolveDelegate(resolver.Resolve); AsyncCallback cb = new AsyncCallback(this.AsyncCustomCallbackMethod); // Begin the method's execution...when finished, the callback will be // called. IAsyncResult ar = synchMethod.BeginInvoke(host, cb, null); break; } case CallbackOption.UseFrameworkSuppliedSynchronousMethod: { Console.WriteLine("Resolving..."); // This calls the synchronous version of a framework-defined class // that also explicitly supports asynchronous invocation. try { hostInformation = Dns.Resolve(host); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break; } case CallbackOption.UseFrameworkSuppliedAsynchronousMethodWithWait: { Console.Write("Resolving"); IAsyncResult ar = Dns.BeginResolve(host, null, null); // Write another period for each 100ms interval of wait time. while (!ar.AsyncWaitHandle.WaitOne(100, false)) { Console.Write("."); } Console.WriteLine(); // If any exceptions are raised by the called method, they won't // be thrown until the results are obtained. try { hostInformation = Dns.EndResolve(ar); DisplayResults(hostInformation); } catch (System.Net.Sockets.SocketException) { Console.WriteLine("Bad host name (SocketException)"); resultsDisplayed = true; } break; } case CallbackOption.UseFrameworkSuppliedAsynchronousMethodWithCallback: { Console.WriteLine("Resolving..."); AsyncCallback cb = new AsyncCallback(this.AsyncFrameworkCallbackMethod); // Begin the call...when it is finished, the callback method will be // called. IAsyncResult ar = Dns.BeginResolve(host, cb, null); break; } default: Console.WriteLine("Not Implemented Yet"); break; } // If this method ends now, there is no guarantee that the host information // will be displayed before the next prompt to the user for more hosts to // resolve is shown. In order to force the wait, put the thread to sleep // for 100ms intervals until the output has been displayed. while (!resultsDisplayed) { // For the synchronous options, this will never get executed // because the results will have been displayed before execution // reaches this point. System.Threading.Thread.Sleep(100); } }