Cluj München 1140km

Gânduri clujene din Bavaria

München - Munich - Monaco di Baviera

19. ianuarie 2009 13:30
by skorpionking
0 Comentarii

.NET 60 seconds code: DNS Lookup with C# sync and async

19. ianuarie 2009 13:30 by skorpionking | 0 Comentarii

Here is how to do a DNS lookup with C# 3.5:

                        try
                        {

                            // sync
                            IPHostEntry iphe = Dns.GetHostEntry(url);

                            string buffer = iphe.HostName;
                            foreach (IPAddress addrs in iphe.AddressList)
                            {
                                // do whatever you want
                            }

                        }
                        catch (Exception ex)
                        {
                           
                        }

Usually you want to do a async lookup, such that your program remains responsive:

                        try
                        {
                            // async
                            AsyncCallback OnResolved =  new AsyncCallback(Resolved);
                            Object state = new Object();
                            Dns.BeginGetHostEntry(url, OnResolved, state);

                        }
                        catch (Exception ex)
                        {

                        }

          private void Resolved(IAsyncResult ar)
          {
               try
               {
                   IPHostEntry iphe = Dns.EndGetHostEntry(ar);

                   string buffer = iphe.HostName;
                   foreach (IPAddress addrs in iphe.AddressList)
                   {
                        // do wahtever you want
                   }
               }
               catch (Exception ex) {
               
               }
          }

Happy coding :-)

Adaugă comentariu

biuquote
Loading