完整的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。为什么输出不同?
当您在foreach循环中将值分配给TextBox
时,可能会发生最后一项现在可以IP
的情况,因此(空IP)将被添加到您的TextBox
中。
因此,请在将项目添加到TextBox
之前添加支票
替换此:
Gateway_Address.Text = d.Address.ToString();
具有以下功能:
if(d.Address.ToString().Trim().Length>2)//ignore ::
Gateway_Address.Text = d.Address.ToString();
在第二个代码段中,您将使用MessageBox
显示每个IP
,因此您可以看到介于两者之间的IP-Address
。
Gateway_Address.Text += d.Address.ToString() + "rn";
或
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("rn", nis);