Search code examples
c#winformsipnslookup

Why can't I print out all ip addresses from a nslookup in c#


Hello I have a question i'm trying to get all ip addresses of an nslookup domain. I'm using the following script in c# on a button but it only prints out 1 ip address, what am I doing wrong?

string myHost = "domain.com";
string myIP = null;


for (int i = 0; i <= System.Net.Dns.GetHostEntry(myHost).AddressList.Length - 1; i++)
{
    if (System.Net.Dns.GetHostEntry(myHost).AddressList[i].IsIPv6LinkLocal == false)
    {
        //myIP = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
        txtIp.Text = System.Net.Dns.GetHostEntry(myHost).AddressList[i].ToString();
    }
}

All help would be greatfull because I've seen mutiple answers here on stackoverflow but I can't get one to work properly.

regards, Dennis


Solution

  • First of all, you should avoid making the dns request 3 times. Store the result in a variable.

    Second, you set txtIp.Text to the last entry. You need to append the strings, but you replace them. Try this code:

    string myHost = "domain.com";
    string myIP = null;
    IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(myHost);
    
    for (int i = 0; i <= hostEntry.AddressList.Length - 1; i++)
    {
        if (!hostEntry.AddressList[i].IsIPv6LinkLocal)
        {
            txtIp.Text += hostEntry.AddressList[i].ToString();
        }
    }
    

    But this can still be shortened to this:

    string myHost = "domain.com";
    string myIP = null;
    IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(myHost);
    txtIP.Text = string.Join(", ", hostEntry.AddressList.Where(ip => !ip.IsIPv6LinkLocal).Select(ip => ip.ToString()));
    

    This gives you a comma-separated list of the ip addresses.