0

在这里完成 nube。刚学:)

我做了一些研究,但无法得到答案。

我正在尝试在文本框中显示我的网关 IP。这是我的代码(从片段构建):

foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
    if (f.OperationalStatus == OperationalStatus.Up)
        foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)

         Gateway_Address.Text = d.Address.ToString();

文本框只显示“::”

现在,如果我使用(从另一个线程复制):

foreach (NetworkInterface f in NetworkInterface.GetAllNetworkInterfaces())
    if (f.OperationalStatus == OperationalStatus.Up)
        foreach (GatewayIPAddressInformation d in f.GetIPProperties().GatewayAddresses)
            MessageBox.Show(d.Address.ToString());

消息框显示 IP。为什么输出不同?

4

2 回答 2

1

当您TextBox在 foreach 循环中分配值时,可能会发生对于最后一项,现在可以完全存在,IP因此(空 IP)将被添加到您的TextBox.

所以请在添加项目之前添加一个检查TextBox

替换这个:

Gateway_Address.Text = d.Address.ToString();

有以下内容:

if(d.Address.ToString().Trim().Length>2)//ignore ::
Gateway_Address.Text = d.Address.ToString();

在您的第二个片段中,您正在显示每个IP使用,MessageBox因此您可以看到IP-Address介于两者之间的。

于 2013-11-14T03:54:03.497 回答
0
Gateway_Address.Text += d.Address.ToString() + "\r\n";

或者

var nis = System.Net.NetworkInformation
            .NetworkInterface.GetAllNetworkInterfaces()
            .Select(s =>
                string.Format("{0}: {1}", s.Name,
                string.Join(";", s.GetIPProperties().GatewayAddresses.Select(ss => ss.Address.ToString()))));

Gateway_Address.Text = string.Join("\r\n", nis);
于 2013-11-14T04:13:29.360 回答