Ejemplo n.º 1
0
/* Here we simply tell the program what must happen when the button is clicked.
 * Obviously in the following case, what happens is that when the button is clicked
 * we invoke a method called "Dns.BeginResolve" which actually finished the real task started
 * by the AsyncCallback delegate, which is to
 * find the IP address of the website */
    void ButtonResolveOnClick(object obj, EventArgs ea)
    {
        results.Items.Clear();
        string addr  = address.Text;
        Object state = new Object();

        Dns.BeginResolve(addr, OnResolved, state);
    }
Ejemplo n.º 2
0
        public void AsyncResolve()
        {
            IAsyncResult async = Dns.BeginResolve(site1Dot, null, null);
            IPHostEntry  entry = Dns.EndResolve(async);

            SubTestValidIPHostEntry(entry);
            CheckIPv4Address(entry, IPAddress.Parse(site1Dot));
        }
Ejemplo n.º 3
0
        // Determine the Internet Protocol (IP) addresses for
        // this host asynchronously.
        public void DoGetHostEntryAsync(string hostname, DnsLookupCallback callback)
        {
            GetHostEntryFinished.Reset();
            ResolveState ioContext = new ResolveState(hostname, callback);

            Dns.BeginResolve(ioContext.host,
                             new AsyncCallback(GetHostEntryCallback), ioContext);
        }
Ejemplo n.º 4
0
        private void btnResolve_Click(object sender, EventArgs e)
        {
            results.Items.Clear();                     // xóa list view
            string addr  = address.Text;               // lấy chuỗi địa chỉ được nhập vào
            Object state = new Object();               // object trạng thái

            Dns.BeginResolve(addr, OnResolved, state); // bắt đầu gửi yêu cầu không đồng bộ DNS đến địa chỉ được nhập vào
        }
Ejemplo n.º 5
0
        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);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Begins an asynchronous request to resolve a DNS host name or IP address in dotted-quad notation to an IPAddress instance.
 /// </summary>
 /// <param name="host">The host to resolve.</param>
 /// <param name="callback">The method to call when the hostname has been resolved.</param>
 /// <returns>An IAsyncResult instance that references the asynchronous request.</returns>
 /// <exception cref="SocketException">There was an error while trying to resolve the host.</exception>
 internal AsyncProxyResult BeginDns(string host, HandShakeComplete callback)
 {
     try {
         Dns.BeginResolve(host, new AsyncCallback(OnResolved), this);
         return(new AsyncProxyResult());
     } catch {
         throw new SocketException();
     }
 }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
0
 public ServerSync(ServerProfile server, AccountProfile account, ShardProfile shard)
 {
     this.m_Server         = server;
     this.m_Account        = account;
     this.m_Shard          = shard;
     this.m_Buffer         = new byte[0x800];
     this.m_CryptoProvider = new LoginCrypto((uint)Network.ClientIP);
     Dns.BeginResolve(server.Address, new AsyncCallback(this.OnResolve), null);
 }
Ejemplo n.º 9
0
        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]);
        }
Ejemplo n.º 10
0
        private void callbackOnNewPC(PC pc)
        {
            object[] objArray = new object[1] {
                (object)pc
            };
            ArpForm arpForm = this;

            arpForm.Invoke((Delegate) new delegateOnNewPC(arpForm.AddPc), objArray);
            Dns.BeginResolve(pc.ip.ToString(), new AsyncCallback(this.EndResolvCallBack), pc);
        }
Ejemplo n.º 11
0
        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());
        }
Ejemplo n.º 12
0
    public static void Main()
    {
        AsyncCallback OnResolved;

        OnResolved = new AsyncCallback(Resolved);

        string addr  = "www.java2s.com";
        Object state = new Object();

        Dns.BeginResolve(addr, OnResolved, state);
    }
Ejemplo n.º 13
0
        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());
        }
Ejemplo n.º 14
0
        /// <summary>
        ///   Begins an asynchronous request to resolve a DNS host name or IP address in dotted-quad notation to an IPAddress instance.
        /// </summary>
        /// <param name = "host">The host to resolve.</param>
        /// <param name = "callback">The method to call when the hostname has been resolved.</param>
        /// <returns>An IAsyncResult instance that references the asynchronous request.</returns>
        /// <exception cref = "SocketException">There was an error while trying to resolve the host.</exception>
        internal IAsyncProxyResult BeginDns(string host, Action <Exception> callback)
        {
            try
            {
                Dns.BeginResolve(host, OnResolved, this);

                return(new IAsyncProxyResult());
            }
            catch
            {
                throw new SocketException();
            }
        }
Ejemplo n.º 15
0
 public void BeginResolve_HostName_Null()
 {
     try {
         Dns.BeginResolve((string)null,
                          new AsyncCallback(ResolveCallback),
                          null);
         Assert.Fail("#1");
     } catch (ArgumentNullException ex) {
         Assert.AreEqual(typeof(ArgumentNullException), ex.GetType(), "#2");
         Assert.IsNull(ex.InnerException, "#3");
         Assert.IsNotNull(ex.Message, "#4");
         Assert.AreEqual("hostName", ex.ParamName, "#5");
     }
 }
Ejemplo n.º 16
0
        public void fBeginResolve(string HostName)
        {
            try
            {
                allDone = new System.Threading.ManualResetEvent(false);

                // 建立 State 物件
                RequestState State = new RequestState();

                // 開始ansyc 解析 DNS
                // 定義Callback 方法為 ResponseCallback
                IAsyncResult Result = Dns.BeginResolve(HostName, new AsyncCallback(ResponseCallback), State);


                int i = 0;
                while (State.host == null)
                {
                    Console.WriteLine(i.ToString());
                    ++i;
                }

                // Wait until asynchronous call completes.
                //allDone.WaitOne();


                string IPAddr   = "";
                string DNS      = ""; // 永久為空
                string hostName = State.host.HostName;
                string result   = "";

                foreach (var item in State.host.AddressList)
                {
                    IPAddr += item.ToString() + "\n\r";
                }

                foreach (var item in State.host.Aliases)
                {
                    DNS += item.ToString() + "\n\r";
                }

                result = "我的IP位置: " + IPAddr + "\n\r" + "我的網域名稱(DNS): \n\r" + DNS + "\n\r" + "我的電腦名稱: " + HostName;

                MessageBox.Show(result);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 17
0
        public void AsyncResolve()
        {
            message = "AsyncResolve";
            reset.Reset();
            IAsyncResult r = Dns.BeginResolve(site, new AsyncCallback(ResolveCallback), null);

            Assert.IsNotNull(r, "IAsyncResult");
            // note for some reason r.AsyncWaitHandle.Wait won't work as expected
            // if (!r.AsyncWaitHandle.WaitOne (timeout, true))
            if (!reset.WaitOne(timeout, true))
            {
                Assert.Ignore("Timeout");
            }
            Assert.IsNull(message, message);
        }
Ejemplo n.º 18
0
        private void Write()
        {
            while (true)
            {
                listBox1.Items.Clear();
                string f, l;
                f = maskedTextBox1.Text.Replace(" ", "");
                l = maskedTextBox2.Text.Replace(" ", "");

                IPAddress        ipf = IPAddress.Parse(f);
                IPAddress        ipl = IPAddress.Parse(l);
                List <IPAddress> ips = new List <IPAddress>();

                //Show IP
                IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
                listBox1.Items.Add("My IP address is " + IPHost.AddressList[0].ToString());

                //Ping using ping class
                ips.Add(ipf);
                IPAddress iph = ipf;
                while (true)
                {
                    iph = increament(iph);
                    if (iph.Address == ipl.Address)
                    {
                        break;
                    }
                    //     iph.Address = iph.Address + 0x1 <<1;
                    ips.Add(iph);
                }


                ips.Add(ipl);
                foreach (IPAddress ip in ips)
                {
                    Ping      pi = new Ping();
                    PingReply pr = pi.Send(ip);

                    Dns.BeginResolve(ip.ToString(), new AsyncCallback(bringname), ip.ToString() + "   " + pr.Status.ToString());
                }
                Thread.Sleep(500);
            }
        }
Ejemplo n.º 19
0
 private void BeginResolve()
 {
     if (State != ClientState.Disconnected)
     {
         try
         {
             _currentAsyncResult = Dns.BeginResolve(_server, null, null);
             InvokeAfterWait(new MethodInvoker(EndResolve), _currentAsyncResult.AsyncWaitHandle);
         }
         catch (Exception e)
         {
             if (!HandleException(e))
             {
                 throw new AsyncTcpClientException(this, e);
             }
             OnResolveFailed();
             return;
         }
     }
 }
Ejemplo n.º 20
0
        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");
        }
Ejemplo n.º 21
0
    public static void Main()
    {
        allDone = new ManualResetEvent(false);
        // Create an instance of the RequestState class.
        RequestState myRequestState = new RequestState();

        // Begin an asynchronous request for information like host name, IP addresses, or
        // aliases for specified the specified URI.
        IAsyncResult asyncResult = Dns.BeginResolve("www.contoso.com", new AsyncCallback(RespCallback), myRequestState);

        // Wait until asynchronous call completes.
        allDone.WaitOne();
        Console.WriteLine("Host name : " + myRequestState.host.HostName);
        Console.WriteLine("\nIP address list : ");
        for (int index = 0; index < myRequestState.host.AddressList.Length; index++)
        {
            Console.WriteLine(myRequestState.host.AddressList[index]);
        }
        Console.WriteLine("\nAliases : ");
        for (int index = 0; index < myRequestState.host.Aliases.Length; index++)
        {
            Console.WriteLine(myRequestState.host.Aliases[index]);
        }
    }
Ejemplo n.º 22
0
 public void PermitOnly_BeginResolve()
 {
     Dns.BeginResolve(null, null, null);
 }
Ejemplo n.º 23
0
 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);
 }
Ejemplo n.º 24
0
        /// <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);
            }
        }
Ejemplo n.º 25
0
        public void DnsObsoleteBeginResolve_BadName_Throws()
        {
            IAsyncResult asyncObject = Dns.BeginResolve("BadName", null, null);

            Assert.ThrowsAny <SocketException>(() => Dns.EndResolve(asyncObject));
        }
Ejemplo n.º 26
0
 public void Deny_BeginResolve()
 {
     Dns.BeginResolve(null, null, null);
 }