Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to avoid SocketException try/catch?

Tags:

c#

.net

dns

host

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!

like image 366
CBrown77 Avatar asked Sep 08 '26 20:09

CBrown77


1 Answers

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.

like image 73
Jesse Spears Avatar answered Sep 11 '26 11:09

Jesse Spears