예제 #1
0
        public static void GetHostEntryDemo()
        {
            string[] args = { };
            if (args.Length == 0 || args[0].Length == 0)
            {
                Console.WriteLine(@"You must specify the name of a host computer.");
                return;
            }
            IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);

            Console.WriteLine(@"Processing request for information...");

            while (result.IsCompleted != true)
            {
                Console.Write("运行中。。。。。");

                Console.ReadKey();
            }

            Console.WriteLine();
            try
            {
                IPHostEntry host      = Dns.EndGetHostEntry(result);
                string[]    aliases   = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine(@"Aliases");
                    foreach (string t in aliases)
                    {
                        Console.WriteLine(t);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine(@"Addresses");
                    foreach (IPAddress t in addresses)
                    {
                        Console.WriteLine(t);
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(@"An exception occurred while processing the request: {0}", e.Message);
            }
        }
예제 #2
0
        public static void Main(string[] args)
        {
            // Make sure the caller supplied a host name.
            if (args.Length == 0 || args[0].Length == 0)
            {
                // Print a message and exit.
                Console.WriteLine("You must specify the name of a host computer.");
                return;
            }
            // Start the asynchronous request for DNS information.
            IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);

            Console.WriteLine("Processing request for information...");
            // Wait until the operation completes.
            result.AsyncWaitHandle.WaitOne();
            // The operation completed. Process the results.
            try
            {
                // Get the results.
                IPHostEntry host      = Dns.EndGetHostEntry(result);
                string[]    aliases   = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("Aliases");
                    for (int i = 0; i < aliases.Length; i++)
                    {
                        Console.WriteLine("{0}", aliases[i]);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses");
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine("{0}", addresses[i].ToString());
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Exception occurred while processing the request: {0}",
                                  e.Message);
            }
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
예제 #3
0
        static void Main(string[] args)
        {
            if (args.Length == 0 || args[0].Length == 0)
            {
                Console.WriteLine("You must specify the name of a host computer.");
                return;
            }

            IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);

            Console.WriteLine("Processing request for information...");

            //폴링
            //업데이트가 끝날때까지 (".") 출력
            while (result.IsCompleted != true)
            {
                UpdateUserInterface();
            }

            Console.WriteLine();
            try
            {
                IPHostEntry host      = Dns.EndGetHostEntry(result);
                string[]    aliases   = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("Aliases");
                    for (int i = 0; i < aliases.Length; i++)
                    {
                        Console.WriteLine("{0}", aliases[i]);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses");
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine("{0}", addresses[i].ToString());
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("An exception occurred while processing the request: {0}", e.Message);
            }
        }
예제 #4
0
            public static void Main(string[] args)
            {
                string queryFQDN = "www.microsoft.com";

                // 開始請求非同步呼叫,查詢DNS資訊

                // 呼叫 BeginXXX 啟動非同步工作
                IAsyncResult result = Dns.BeginGetHostEntry(queryFQDN, null, null);

                Console.WriteLine("正在取得與處理DNS的資訊...");

                // 因為執行緒沒有被封鎖住,您可以在這裡處理其他工作

                try
                {
                    // 直接呼叫 EndXXX 方法,直接等候非同步的處理最後結果(也許是成功、也許是失敗)
                    // 不過此時的 Thread 是被鎖定的,也就是無法繼續執行其他工作
                    // 一旦,執行緒解除鎖定,也就是非同步處理作業完成了(也許成功,也許失敗),就可以繼續執行
                    IPHostEntry host      = Dns.EndGetHostEntry(result);
                    string[]    aliases   = host.Aliases;
                    IPAddress[] addresses = host.AddressList;
                    if (aliases.Length > 0)
                    {
                        Console.WriteLine("別名");
                        for (int i = 0; i < aliases.Length; i++)
                        {
                            Console.WriteLine("{0}", aliases[i]);
                        }
                    }
                    if (addresses.Length > 0)
                    {
                        Console.WriteLine("位址");
                        for (int i = 0; i < addresses.Length; i++)
                        {
                            Console.WriteLine("{0}", addresses[i].ToString());
                        }
                    }
                }
                catch (SocketException e)
                {
                    Console.WriteLine("當處理請求的時候,異常發生了: {0}", e.Message);
                }

                Console.WriteLine("Press any key for continuing...");
                Console.ReadKey();
            }
예제 #5
0
 private string fetchFQHN()
 {
     try
     {
         var result  = Dns.BeginGetHostEntry(HostnameOrIpAddress, null, null);
         var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5));
         if (!success)
         {
             throw new Exception("Can't get DNS Entry");
         }
         return(Dns.EndGetHostEntry(result).HostName);;
     }
     catch (Exception)
     {
         return(HostnameOrIpAddress);
     }
 }
예제 #6
0
 private IPAddress[] fetchIPv4Adresses()
 {
     try
     {
         var result  = Dns.BeginGetHostAddresses(HostnameOrIpAddress, null, null);
         var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5));
         if (!success)
         {
             throw new Exception("Can't get DNS Entry");
         }
         return(Dns.EndGetHostEntry(result).AddressList);;
     }
     catch (Exception)
     {
         return(new IPAddress[] { });
     }
 }
예제 #7
0
 /// <summary>
 /// Record the IPs in the state object for later use.
 /// </summary>
 private void GetHostEntryCallback(IAsyncResult ar)
 {
     try
     {
         DnsResponse dnsResponse = (DnsResponse)ar.AsyncState; // Turn the state object into the DnsResponse type
         dnsResponse.IpHostEntry = Dns.EndGetHostEntry(ar);    // Save the returned IpHostEntry and populate other fields based on its parameters
         dnsResponse.CallComplete.Set();                       // Set the wait handle so that the caller knows that the asynchronous call has completed and that the response has been updated
     }
     catch (SocketException ex)
     {
         LogMessage("GetHostEntryCallback", $"Socket Exception: {ex.Message}");
     }
     catch (Exception ex)
     {
         LogMessage("GetHostEntryCallback", $"Exception: {ex}");
     } // Log exceptions but don't throw them
 }
예제 #8
0
        // Record the IPs in the state object for later use.
        public static void GetHostEntryCallback(IAsyncResult ar)
        {
            ResolveState ioContext = (ResolveState)ar.AsyncState;

            try
            {
                ioContext.IPs = Dns.EndGetHostEntry(ar);
                GetHostEntryFinished.Set();
            }
            catch (Exception ex)
            {
                ioContext = null;
                Debug.WriteLine("Errorr");

                //   GetHostEntryFinished.Set();
            }
        }
        protected override void getResponse(IAsyncResult __result)
        {
            IPHostEntry ipEntry = null;

            switch (action)
            {
            case webRequestActionType.CheckUrlOnly:
                ipEntry = Dns.EndGetHostEntry(__result);
                if (ipEntry != null)
                {
                    result.document.deploySource("Exists", action);
                }
                break;

            case webRequestActionType.ipResolve:
                ipEntry = Dns.EndGetHostEntry(__result);
                //dnsLookupDocument dLD = new dnsLookupDocument(ipEntry, urlObject.DnsSafeHost);
                // result.dataObject = dLD;
                throw new NotImplementedException();
                String xmlVersion = "";     // objectSerialization.ObjectToXML(dLD);  //imbSerialization.serializeValue(dLD, imbSerializationMode.XML).ToString();
                result.document.deploySource(xmlVersion, action);
                break;

            case webRequestActionType.whoIs:
                tcpClient.EndConnect(__result);
                StringBuilder sb = new StringBuilder();

                BufferedStream bufferedStreamWhois = new BufferedStream(tcpClient.GetStream());
                StreamWriter   streamWriter        = new StreamWriter(bufferedStreamWhois);

                streamWriter.WriteLine(url);
                streamWriter.Flush();

                StreamReader streamReaderReceive = new StreamReader(bufferedStreamWhois);

                while (!streamReaderReceive.EndOfStream)
                {
                    sb.AppendLine(streamReaderReceive.ReadLine());
                }

                result.document.deploySource(sb.ToString(), action);

                break;
            }
        }
예제 #10
0
        bool checkHost(ref HostParms hostParms)
        {
            bool        bRet   = false;
            IPHostEntry ipHost = new IPHostEntry();

            try
            {
                IPHostEntry entry = null;
                int         maxSeconds = hostParms.retry /* 10 */, counter = 0;
                // see http://jianmingli.com/wp/?p=22
                // Start the asynchronous request for DNS information.
                // This example does not use a delegate or user-supplied object
                // so the last two arguments are null.
                IAsyncResult result = Dns.BeginGetHostEntry(hostParms.host /* ipAddress */, null, null);
                // Poll for completion information.
                while (result.IsCompleted != true && counter < maxSeconds)
                {
                    Thread.Sleep(1000);
                    counter++;
                }
                if (result.IsCompleted)                  //when we got here, the result is ready
                {
                    entry = Dns.EndGetHostEntry(result); //blocks?
                }
                else
                {
                    hostParms.isValid = false; // Thread.CurrentThread.Abort();
                }
                //IPHostEntry entry = Dns.Resolve(hostNameOrAddress);
                //IPHostEntry entry = Dns.GetHostEntry(ipAddress);
                hostParms.ipAddress = entry.AddressList[0];
                hostParms.isValid   = true;
            }
            catch (ThreadAbortException e)
            {
                Thread.CurrentThread.Abort();// ("DNS failed within timeout", e);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(string.Format("Exception in checkHost({0}): {1}", hostParms.host, e.Message));
                //throw new PingUnknownHostException("Impossible to resolve host or address.", e);
            }

            return(hostParms.isValid);
        }
예제 #11
0
        public static void Main(string[] args)
        {
            string queryFQDN = "www.microsoft.com";

            // Start the asynchronous request for DNS information.
            // 呼叫 BeginXXX 啟動非同步工作
            IAsyncResult result = Dns.BeginGetHostEntry(queryFQDN, null, null);

            Console.WriteLine("Processing request for information...");
            // Wait until the operation completes.
            // 當執行下面程式碼時候,整個 Thread 會被 Block,這個Thread要能繼續執行,必須等候到非同步工作完成
            result.AsyncWaitHandle.WaitOne();

            // The operation completed. Process the results.
            try
            {
                // Get the results.
                // 由於非同步工作已經完成了,所以,我們在此呼叫了 EndXXX 方法,取得非同步工作的處理結果
                IPHostEntry host      = Dns.EndGetHostEntry(result);
                string[]    aliases   = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("Aliases");
                    for (int i = 0; i < aliases.Length; i++)
                    {
                        Console.WriteLine("{0}", aliases[i]);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses");
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine("{0}", addresses[i].ToString());
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("Exception occurred while processing the request: {0}",
                                  e.Message);
            }
            Console.ReadKey();
        }
예제 #12
0
        static void ProcessDnsInformation(IAsyncResult result)
        {
            HostRequest request = (HostRequest)result.AsyncState;

            try
            {
                IPHostEntry host = Dns.EndGetHostEntry(result);
                request.HostEntry = host;
            }
            catch (SocketException e)
            {
                request.ExceptionObject = e;
            }
            finally
            {
                Interlocked.Decrement(ref requestCounter);
            }
        }
예제 #13
0
        private void ResolveHostAsync_Callback(IAsyncResult ar)
        {
            _remoteHostEntry = Dns.EndGetHostEntry(ar);

            if (_remoteHostEntry.AddressList.Length > 0)
            {
                Logger.Network.Debug("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nRemote host resolved to " + _remoteHostEntry.AddressList[0].ToString());
            }
            else
            {
                Logger.Network.Warn("HttpConnection ID: " + this.GetHashCode().ToString() + "\r\nResolved remote host without any results.");
            }

            if (OnHostResolved != null)
            {
                OnHostResolved(this, _remoteHostEntry);
            }
        }
예제 #14
0
    // Token: 0x06000752 RID: 1874 RVA: 0x0003AB8C File Offset: 0x00038D8C
    private void OnHostLookupDone(IAsyncResult res)
    {
        IPHostEntry iphostEntry = Dns.EndGetHostEntry(res);

        if (this.m_abort)
        {
            ZLog.Log("Host lookup abort");
            return;
        }
        if (iphostEntry.AddressList.Length == 0)
        {
            this.m_dnsError = true;
            ZLog.Log("Host lookup adress list empty");
            return;
        }
        this.m_socket = ZSocket2.CreateSocket();
        this.m_result = this.m_socket.BeginConnect(iphostEntry.AddressList, this.m_port, null, null);
    }
예제 #15
0
        public static Task <IPHostEntry> GetHostEntryAsync(string hostNameOrAddress)
        {
            TaskCompletionSource <IPHostEntry> tcs = new TaskCompletionSource <IPHostEntry>();

            Dns.BeginGetHostEntry(hostNameOrAddress, asyncResult =>
            {
                try
                {
                    IPHostEntry result = Dns.EndGetHostEntry(asyncResult);
                    tcs.SetResult(result);
                }
                catch (Exception e)
                {
                    tcs.SetException(e);
                }
            }, null);
            return(tcs.Task);
        }
예제 #16
0
파일: Program.cs 프로젝트: kisubkim/C_Sharp
        static void Main(string[] args)
        {
            //Web 관련 Test 진행할것.
            Console.Write("Enter Host Name (ex> www.naver.com) : ");
            string      strDomainName = Console.ReadLine();
            IPHostEntry host          = null;

            try
            {
                host = Dns.GetHostEntry(strDomainName);
            }
            catch
            {
                Console.WriteLine("Dns.GetHostEntry() function Retuen Error. Check Please.");
            }

            Console.WriteLine("------------- 처리 결과 --------------");
            Console.WriteLine("Host Name : " + strDomainName);
            Console.WriteLine("IP Address : ");
            for (int i = 0; i < host.AddressList.Length; i++)
            {
                IPAddress ipAdd = host.AddressList[i];
                Console.WriteLine("[" + i + "] = " + ipAdd.ToString());
            }

            Console.WriteLine("------------- 처리 2 진행 ----------------------");
            Console.Write("Enter Host IP (ex> 192.168.100.100) : ");
            IPAddress ip = IPAddress.Parse(Console.ReadLine());


            try
            {
                IAsyncResult iResult = null;
                Dns.EndGetHostEntry(iResult);
                host = Dns.GetHostEntry(ip);
            }
            catch
            {
                Console.WriteLine("Dns.GetHostEntry() function Retuen Error. (In 2nd).");
            }

            Console.WriteLine("Host IP : " + ip);
            Console.WriteLine("Host Name : " + host.HostName);
        }
예제 #17
0
        public static void Main(string[] args)
        {
            // Make sure the caller supplied a host name.
            if (args.Length == 0 || args[0].Length == 0)
            {
                // Print a message and exit.
                Console.WriteLine("You must specify the name of a host computer.");
                return;
            }
            // Start the asynchronous request for DNS information.
            // This example does not use a delegate or user-supplied object
            // so the last two arguments are null.
            IAsyncResult result = Dns.BeginGetHostEntry(args[0], null, null);

            Console.WriteLine("Processing your request for information...");
            // Do any additional work that can be done here.
            try
            {
                // EndGetHostByName blocks until the process completes.
                IPHostEntry host      = Dns.EndGetHostEntry(result);
                string[]    aliases   = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("Aliases");
                    for (int i = 0; i < aliases.Length; i++)
                    {
                        Console.WriteLine("{0}", aliases[i]);
                    }
                }
                if (addresses.Length > 0)
                {
                    Console.WriteLine("Addresses");
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine("{0}", addresses[i].ToString());
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("An exception occurred while processing the request: {0}", e.Message);
            }
        }
예제 #18
0
            public static void Main(string[] args)
            {
                string queryFQDN = "www.microsoft.com";

                // Start the asynchronous request for DNS information.
                // This example does not use a delegate or user-supplied object
                // so the last two arguments are null.
                // 呼叫 BeginXXX 啟動非同步工作
                IAsyncResult result = Dns.BeginGetHostEntry(queryFQDN, null, null);

                Console.WriteLine("Processing your request for information...");
                // Do any additional work that can be done here.
                try
                {
                    // EndGetHostByName blocks until the process completes.
                    // 直接呼叫 EndXXX 方法,直接等候非同步的處理最後結果(也許是成功、也許是失敗)
                    // 不過此時的 Thread 是被鎖定的,也就是無法繼續執行其他工作
                    IPHostEntry host      = Dns.EndGetHostEntry(result);
                    string[]    aliases   = host.Aliases;
                    IPAddress[] addresses = host.AddressList;
                    if (aliases.Length > 0)
                    {
                        Console.WriteLine("Aliases");
                        for (int i = 0; i < aliases.Length; i++)
                        {
                            Console.WriteLine("{0}", aliases[i]);
                        }
                    }
                    if (addresses.Length > 0)
                    {
                        Console.WriteLine("Addresses");
                        for (int i = 0; i < addresses.Length; i++)
                        {
                            Console.WriteLine("{0}", addresses[i].ToString());
                        }
                    }
                }
                catch (SocketException e)
                {
                    Console.WriteLine("An exception occurred while processing the request: {0}", e.Message);
                }

                Console.ReadKey();
            }
예제 #19
0
        private static void ProcessDnsInformation(IAsyncResult result)
        {
            string hostName = (string)result.AsyncState;

            HostNames.Add(hostName);
            try
            {
                IPHostEntry host = Dns.EndGetHostEntry(result);
                HostData.Add(host);
            }
            catch (SocketException e)
            {
                HostData.Add(e.Message);
            }
            finally
            {
                Interlocked.Decrement(ref _requestCounter);
            }
        }
예제 #20
0
 private void DnsReceived(IAsyncResult result)
 {
     if (this.SocketConnected)
     {
         try
         {
             IPHostEntry i = Dns.EndGetHostEntry(result);
             this.DNS = Helpers.ObfuscateDns(i.HostName);
         }
         catch
         {
             try
             {
                 this.DNS = Helpers.ObfuscateDns(this.ExternalIP.ToString());
             }
             catch { }
         }
     }
 }
예제 #21
0
        /*
         * Metodo per creare una nuova Tab e aggiungerla a quelle visualizzate
         */
        public void addTab(TcpClient client, NetworkStream stream, String indirizzo)
        {
            InteractiveTabItem first = new InteractiveTabItem(this);
            MyTabItem          tab   = new MyTabItem(first);

            first.TabElement = tab;
            // Impostazione header Tab con l'indirizzo IP
            first.NewHeader = first.RemoteHost = indirizzo;
            // Se l'indirizzo è di loopback, viene visualizzato nell'header
            if (indirizzo.StartsWith("127."))
            {
                first.NewHeader = "Loopback";
            }
            else
            {
                // Tentativo di risoluzione del nome host
                Dns.BeginGetHostEntry(indirizzo,
                                      new AsyncCallback((IAsyncResult ar) => {
                    try {
                        // Se la risoluzione è riuscita, il nome host viene visualizzato nell'header
                        string hostName = Dns.EndGetHostEntry(ar).HostName;
                        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => { first.NewHeader = hostName; }));
                    } catch (SocketException) {
                        // Se non viene trovato un nome host, la tab mantiene l'indirizzo come header
                        Console.WriteLine("Server {0}: Nessun nome host trovato", indirizzo);
                    }
                }), null);
            }

            tab.Connection = client;
            tab.Stream     = stream;
            tab.startWork();
            first.Content = tab;
            // Aggiunta della Tab tra quelle visualizzate
            tabItems.Add(first);
            // Viene evidenziata l'ultima tab creata
            tabControl.SelectedIndex = tabItems.Count - 1;
            // Nel caso ci siano più tab, attiviamo la scelta dell'app in foreground tramite checkbox
            if (tabItems.Count > 1)
            {
                foregroundBox.IsEnabled = true;
            }
        }
예제 #22
0
 private void OnResolved(IAsyncResult ar)
 {
     lock (connectLock)
     {
         try
         {
             var port = (int)ar.AsyncState;
             remoteEndPoint = new IPEndPoint(Dns.EndGetHostEntry(ar).AddressList[0], port);
             ContinueConnect();
         }
         catch (Exception e)
         {
             if (DisconnectNow())
             {
                 ConnectFailNotify(e);
             }
         }
     }
 }
예제 #23
0
        public static void PollUntilOperationCompletes(IPAddress ip)
        {
            IAsyncResult result = Dns.BeginGetHostEntry(ip, null, null);

            Console.WriteLine("APM Poll Thread id : {0}, processing request for information...", Thread.CurrentThread.ManagedThreadId);

            //轮询操作
            while (!result.IsCompleted)
            {
                Console.Write(".");
            }
            Console.WriteLine();

            try
            {
                IPHostEntry host      = Dns.EndGetHostEntry(result);
                string[]    aliases   = host.Aliases;
                IPAddress[] addresses = host.AddressList;
                if (aliases.Length > 0)
                {
                    Console.WriteLine("APM Poll Thread id : {0}, Aliases", Thread.CurrentThread.ManagedThreadId);
                    for (int i = 0; i < aliases.Length; i++)
                    {
                        Console.WriteLine("APM Poll Thread id : {0}, {1}", Thread.CurrentThread.ManagedThreadId, aliases[i]);
                    }
                }

                if (addresses.Length > 0)
                {
                    Console.WriteLine("APM Poll Thread id : {0}, address", Thread.CurrentThread.ManagedThreadId);
                    for (int i = 0; i < addresses.Length; i++)
                    {
                        Console.WriteLine("APM Poll Thread id : {0}, {1}", Thread.CurrentThread.ManagedThreadId, addresses[i]);
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine("APM Poll Thread id : {0}, Exception occurred while processing the request: {1}",
                                  Thread.CurrentThread.ManagedThreadId, e.Message);
            }
        }
예제 #24
0
 private void EndDnsReq(IAsyncResult ar)
 {
     try {
         var h = Dns.EndGetHostEntry(ar);
         var v = JSC.JSObject.CreateObject();
         v["Address"] = EndPoint.Address.ToString();
         v["Port"]    = EndPoint.Port;
         v["Dns"]     = h.HostName;
         _owner.SetState(v, _owner);
         Log.Info("{0} connected from {1}[{2}]:{3}", _owner.path, h.HostName, EndPoint.Address.ToString(), EndPoint.Port);
     }
     catch (SocketException) {
         var v = JSC.JSObject.CreateObject();
         v["Address"] = EndPoint.Address.ToString();
         v["Port"]    = EndPoint.Port;
         _owner.SetState(v, _owner);
         Log.Info("{0} connected from {1}:{2}", _owner.path, EndPoint.Address.ToString(), EndPoint.Port);
     }
     Log.Write += Log_Write;
 }
예제 #25
0
        private void GetHostEntryCallback(IAsyncResult ar)
        {
            try
            {
                IPHostEntry hostEntry = null;
                IPAddress[] addresses = null;

                hostEntry    = Dns.EndGetHostEntry(ar);
                addresses    = hostEntry.AddressList;
                this.address = addresses[0];

                form1.SetStatusLabelDelegate("Host name correct!");
            }
            catch (Exception exc)
            {
                MessageBox.Show("3. Exception:\t\n" + exc.Message.ToString());
                form1.SetStatusLabelDelegate("Wrong host name!");
                form1.SetButtonDelegate(true);
            }
        }
예제 #26
0
        private void OnResolve(IAsyncResult ar)
        {
            if (m_state != State.Resolving)
            {
                return;
            }

            try
            {
                IPHostEntry hostEntry = Dns.EndGetHostEntry(ar);

                IPAddress[] addrList = hostEntry.AddressList;

                if (addrList.Length == 0)
                {
                    m_state = State.Disconnected;

                    if (connectEvent != null)
                    {
                        connectEvent(new Exception("Failed to resolve"), m_address, m_port);
                    }

                    return;
                }

                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                IPEndPoint ipEndPoint = new IPEndPoint(addrList[0], m_port);

                m_state = State.Connecting;

                m_socket.BeginConnect(ipEndPoint, new AsyncCallback(OnConnect), 0);
            }
            catch (Exception e)
            {
                if (connectEvent != null)
                {
                    connectEvent(new Exception("Failed to resolve: " + e.Message), m_address, m_port);
                }
            }
        }
예제 #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="Addr"></param>
        /// <returns></returns>
        public static string GetHostname(string Addr)
        {
            lock (Resolved)
            {
                if (Resolved.ContainsKey(Addr))
                {
                    return(Resolved[Addr]);
                }

                Resolved.Add(Addr, Addr);
            }

            try
            {
                Logger.Log(LogLevel.Verbose, LogCategory.Transport, "Resolving hostname '{0}' ...", Addr);
                Dns.BeginGetHostEntry(
                    Addr, DnsResult =>
                {
                    try
                    {
                        IPHostEntry HostEntry = Dns.EndGetHostEntry(DnsResult);
                        lock (Resolved)
                        {
                            Logger.Log(LogLevel.Verbose, LogCategory.Transport, "Resolved '{0}' to '{1}'", Addr, HostEntry.HostName);
                            Resolved[Addr] = HostEntry.HostName;
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.Log(LogLevel.Verbose, LogCategory.Transport, "Failed to resolved hostname '{0}' with error: {1}", Addr, ex.Message);
                    }
                }, null
                    );
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Verbose, LogCategory.Transport, "Failed to resolved hostname '{0}' with error: {1}", Addr, ex.Message);
            }

            return(Addr);
        }
        // The following method is called when each asynchronous operation completes.
        static void ProcessDnsInformation(IAsyncResult result)
        {
            string hostName = (string)result.AsyncState;

            hostNames.Add(hostName);
            try
            {
                // Get the results.
                IPHostEntry host = Dns.EndGetHostEntry(result);
                hostData.Add(host);
            }
            // Store the exception message.
            catch (SocketException e)
            {
                hostData.Add(e.Message);
            } finally
            {
                // Decrement the request counter in a thread-safe manner.
                Interlocked.Decrement(ref requestCounter);
            }
        }
예제 #29
0
        private void GetHost_End(IAsyncResult ar)
        {
            Connect_SO asyncState = (Connect_SO)ar.AsyncState;

            try
            {
                asyncState.UpdateContext();
                IPHostEntry host = Dns.EndGetHostEntry(ar);
                if (host == null)
                {
                    throw new SocketException(0x2af9);
                }
                EndPoint remoteEP = SocketBase.ConstructEndPoint(host, asyncState.Port);
                base._socket.BeginConnect(remoteEP, new AsyncCallback(this.Connect_End), asyncState);
            }
            catch (Exception exception)
            {
                asyncState.Exception = exception;
                asyncState.SetCompleted();
            }
        }
예제 #30
0
        private void GetHostByNameSink(IAsyncResult result)
        {
            IPHostEntry e = null;

            try
            {
                e = Dns.EndGetHostEntry(result);
            }
            catch (Exception ex)
            {
                // Could not resolve?
                OpenSource.Utilities.EventLogger.Log(ex);
                return;
            }

            object[] Args     = (object[])result.AsyncState;
            Uri      Resource = (Uri)Args[0];
            object   Tag      = (object)Args[1];

            ContinueRequest(new IPEndPoint(e.AddressList[0], Resource.Port), HTTPMessage.UnEscapeString(Resource.PathAndQuery), Tag, null);
        }