2012-11-01 37 views
6

我在同步「IP地址和描述」時遇到了問題。使用C獲取IP地址和適配器描述#

目的是這樣的:

獲取IP地址和描述是什麼?

例子:

| 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()); 
      } 
     } 
    } 
} 

我怎樣才能解決這個問題?

+0

我曾嘗試你的代碼,它的工作,你能更詳細地解釋這個問題? –

+0

我不認爲您發佈的代碼存在問題。我已經設法從我的系統上運行的每個網絡設備獲取本地IP :) –

+0

當我們有多個Internet適配器時會發生問題.. –

回答

12

代碼中的問題是,您不使用給定適配器的關聯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()); 
     } 
    } 
} 
+0

這必須是解決方案,就是這樣+1 –

+0

謝謝你的回答@hans ... –

+0

** @ Hans:我有2個問題給你1我們如何防止回送地址在消息框中預覽?第二我如何接受你的答案?大聲笑** –