【问题标题】:Why can't I print out all ip addresses from a nslookup in c#为什么我不能从 c# 中的 nslookup 中打印出所有 IP 地址
【发布时间】:2016-07-21 10:39:58
【问题描述】:

您好,我有一个问题,我正在尝试获取 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();
    }
}

所有帮助都会非常有用,因为我在 stackoverflow 上看到了多个答案,但我无法让一个正常工作。

问候, 丹尼斯

【问题讨论】:

    标签: c# winforms ip nslookup


    【解决方案1】:

    首先,您应该避免发出 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 地址列表。

    【讨论】:

    • 非常感谢,我终于让它按我想要的方式工作了;)
    猜你喜欢
    • 2012-02-25
    • 2016-01-06
    • 1970-01-01
    • 2016-11-30
    • 2022-01-02
    • 2022-09-28
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    相关资源
    最近更新 更多