您好我有一个问题,我正在尝试获取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的多个答案,但是我无法正常工作。
问候,丹尼斯
首先,您应该避免发出dns请求3次。将结果存储在变量中。
其次,您设置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地址列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句