Limit Dns.GetHostAddresses by time

1.6k views Asked by At

i'm writing a script that resolve ip address for domain using C#

the problem is that i have a lot of domains that does not resolve to an IP, so the code (Dns.GetHostAddresses) is running for a long time trying to resolve an IP for a domain that doesn't have an IP.

this is the code:

public string getIPfromHost(string host)
{
    try
    {
        var domain = Dns.GetHostAddresses(host)[0];
        return domain.ToString();
    }
    catch (Exception)
    {
        return "No IP";
    }
}

what i want to do is if there is no IP after 1 sec i want to return "No IP"

how can i achieve that?

2

There are 2 answers

0
Rajput On BEST ANSWER

You can achieve this by using TPL(Task Parallel Library). You can create new task and wait for 1 sec, if it is succeed then return true otherwise false. just use below code in getIPfromHost(string host) this method. (This is solution for your question which needs to wait for 1 sec please ensure your previous method was working fine.)

public string getIPfromHost(string host)
        {
            try
            {
                Task<string> task = Task<string>.Factory.StartNew(() =>
                {
                     var domain = Dns.GetHostAddresses(host)[0];
                     return domain.ToString();
                });

            bool success = task.Wait(1000);
            if (success)
            {
                return task.Result;
            }
            else
            {
                return "No IP";
            }

            }
            catch (Exception)
            {

                return "No IP";
            }

        }
0
andronoid On

Starting with the .NET Framework 4.5, the Dns.GetHostAddressesAsync method can be used instead of Task.Factory.StartNew:

public string getIPfromHost(string host)
{
    try
    {
        var domain = Dns.GetHostAddressesAsync(host)[0];
        bool isTaskComplete = domain.Wait(1000);
        if (isTaskComplete)
        {
            return domain.Result.ToString();
        }
        else // Task timed out
        {
            return "No IP";
        }
    }
    catch (Exception)
    {
        return "No IP";
    }
}