Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit Dns.GetHostAddresses by time

Tags:

c#

system.net

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?

like image 480
Eitanmg Avatar asked Sep 17 '25 09:09

Eitanmg


1 Answers

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";
            }

        }
like image 180
Rajput Avatar answered Sep 19 '25 06:09

Rajput