简体   繁体   中英

Way to avoid SocketException try/catch?

I have been trying to find a way to determine whether or not a string, a hostname, in this example, is indeed a valid hostname and can resolve to an IP. I am using the DNS class in C#, and using the function:

Dns.GetHostEntry(hostname)

However, if this function fails, it throws a SocketException error, and with the list of strings I must deal with, these exceptions can occur quite often. I created a try/catch seen below to handle this:

public List<string> fetchIP(string hostname)
{
    try
    {
        List<string> theIPs = new List<string>();
        IPHostEntry entry = Dns.GetHostEntry(hostname);
        foreach (IPAddress ipAddress in entry.AddressList)
        {
            theIPs.Add(ipAddress.ToString());
        }
        return theIPs;
    }
    catch (System.Net.Sockets.SocketException)
    {
        return null;
    }   
}

Now the problem is... This runs very slow. The page currently takes over 10 seconds to load on average, because of the failed GetHostEntry() calls. Is there any way to know if a hostname can resolve to an IP without doing it the way I have? I cannot find a way to avoid horrible performance.

Sorry if my question is unclear, this is my first asked on this site!

Resolving a hostname is often a time-consuming process. To fully resolve a hostname is unavoidably going to bottleneck on the response time of a remote DNS server if the answer isn't already cached. Your best bet is to either run a local DNS server that would be able to respond immediately (and cache previous requests) or maintain a cache in your code.

Either way, new requests that don't hit the cache will take a long time. A mitigation would be to pre-populate your DNS server with requests you expect to happen. How to do this is outside the scope of this question.

Are you running in 4.5? You could try the Uri.CheckHostName method.

Console.WriteLine(Uri.CheckHostName("www.google.com"));

https://msdn.microsoft.com/en-us/library/system.uri.checkhostname(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM