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?
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";
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With