2017-06-17 73 views
0

我的電腦上有多個網卡。 (由於VMWare)C#獲取活動NIC IPv4地址

如何查找活動卡的IPv4地址。我的意思是,如果我在終端發送ping命令並在WireShark中攔截數據包,我想要「Source」的地址。

我想檢查每個網絡接口,看看GateWay是否爲空或空?或者,也許ping 127.0.0.1並獲得ping請求的IP源?但不能實現它。

現在我有這樣的代碼,我在計算器上

public static string GetLocalIpAddress() 
     { 
      var host = Dns.GetHostEntry(Dns.GetHostName()); 
      return host.AddressList.First(h => h.AddressFamily == AddressFamily.InterNetwork).ToString(); 
     } 

找到,但它讓我在VMware卡的IP。但我不知道還有什麼「.First()」我可以使用。

回答

1

,我終於找到了獲得真正的有效途徑IP。基本上它會查找IPv4中的所有接口,這些接口都是UP和它決定的,它只是將接口與默認網關相連接。

public static string GetLocalIpAddress() 
     { 
      foreach (var netI in NetworkInterface.GetAllNetworkInterfaces()) 
      { 
       if (netI.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && 
        (netI.NetworkInterfaceType != NetworkInterfaceType.Ethernet || 
        netI.OperationalStatus != OperationalStatus.Up)) continue; 
       foreach (var uniIpAddrInfo in netI.GetIPProperties().UnicastAddresses.Where(x => netI.GetIPProperties().GatewayAddresses.Count > 0)) 
       { 

        if (uniIpAddrInfo.Address.AddressFamily == AddressFamily.InterNetwork && 
         uniIpAddrInfo.AddressPreferredLifetime != uint.MaxValue) 
         return uniIpAddrInfo.Address.ToString(); 
       } 
      } 
      Logger.Log("You local IPv4 address couldn't be found..."); 
      return null; 
     } 
0

好了,我的朋友,你可以做到以下幾點:

var nics = NetworkInterface.GetAllNetworkInterfaces(); 
foreach (var networkInterface in nics) 
{ 
    if (networkInterface.OperationalStatus == OperationalStatus.Up) 
    { 
     var address = networkInterface.GetPhysicalAddress(); 
    } 
} 

地址變量,您可以訪問PhysicalAddress目前最多的網絡接口

+0

謝謝你的回答。這種類型的實現的問題是,它會讓你把所有的內部表面都展現出來。而我的其他卡也上漲了。我已經發布了我終於想出的解決方案 – user3673720

+0

是的,但是您已經在問題的代碼示例中選擇了第一個。我的解決方案向你展示了所有的接口,你可以選擇其中的一個。順便說一句,你找到了你的答案,那就是重要的 –