为什么我不能从 C# 中的 nslookup 打印出所有 IP 地址

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

您好,我有一个问题,我正在尝试获取 nslookup 域的所有 IP 地址。我在按钮上使用 C# 中的以下脚本,但它只打印出 1 个 IP 地址,我做错了什么?

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();
    }
}

所有的帮助都会很棒,因为我在 Whosebug 上看到了多个答案,但我无法找到一个正常工作的答案。

此致, 丹尼斯

首先,你应该避免3次的dns请求。将结果存储在变量中。

其次,您将 txtIp.Text 设置为最后一个条目。您需要附加字符串,但您替换了它们。试试这个代码:

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();
    }
}

但这仍然可以缩短为:

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()));

这会为您提供一个以逗号分隔的 IP 地址列表。