C# 使用C获取IP地址和适配器描述#
我在同步“IP地址和描述”时遇到问题 目标是: 获取IP地址,说明是什么 例如:C# 使用C获取IP地址和适配器描述#,c#,networking,ip-address,C#,Networking,Ip Address,我在同步“IP地址和描述”时遇到问题 目标是: 获取IP地址,说明是什么 例如: | Atheros Azx1234 Wireless Adapter | |192.168.1.55 | 但结果不是我所期望的 这是我的代码,请随意尝试 private void button1_Click(object sender, EventArgs e) { NetworkInterface[] interfaces = NetworkInterface
| Atheros Azx1234 Wireless Adapter |
|192.168.1.55 |
但结果不是我所期望的
这是我的代码,请随意尝试
private void button1_Click(object sender, EventArgs e)
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (NetworkInterface adapter in interfaces)
{
foreach (IPAddress ip in host.AddressList)
{
if ((adapter.OperationalStatus.ToString() == "Up") && // I have a problem with this condition
(ip.AddressFamily == AddressFamily.InterNetwork))
{
MessageBox.Show(ip.ToString(), adapter.Description.ToString());
}
}
}
}
如何解决此问题?代码中的问题是您没有使用关联的IP地址 对于给定的适配器。而不是将所有IP地址匹配到每个适配器 仅使用与当前适配器关联的IP地址:
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in interfaces)
{
var ipProps = adapter.GetIPProperties();
foreach (var ip in ipProps.UnicastAddresses)
{
if ((adapter.OperationalStatus == OperationalStatus.Up)
&& (ip.Address.AddressFamily == AddressFamily.InterNetwork))
{
Console.Out.WriteLine(ip.Address.ToString() + "|" + adapter.Description.ToString());
}
}
}
我已经试过了你的代码,它正在运行,你能更详细地解释一下这个问题吗?我认为你发布的代码没有问题。我已设法从在我的系统上运行的每个网络设备获取本地IP:)当我们有多个internet适配器时会出现问题。请参阅“cmd>ipconfig/all”观察消息框,它将重复IP地址消息框必须仅预览计算机的适配器这必须是解决方案,就这样+1**@Hans:我有两个问题要问你:第一,我们如何防止回送地址在消息框中预览?我怎样才能接受你的回答?lol**@RoiseEscalera:您可以通过在if语句中添加以下条件来过滤环回地址:ip.address.Equals(IPAddress.loopback)==false。若要接受我的回答,请单击投票箭头下方的空心复选标记(勾号)。