2015-01-08 106 views
1

我想開發一個通用的基於VB.NET的應用程序,它將返回本地機器的以太網IP地址。我已經提到了在這裏討論的用於獲取機器IP地址的幾個問題,並發現了一些很好的建議。如何區分使用VB.NET的以太網和WiFi IP地址

我面對的問題是,當我運行這個應用程序時,它會返回我WiFi和以太網的IP地址。當我在別人的機器上運行此應用程序時,我無法確定哪個IP地址屬於哪個接口。我只對以太網IP地址感興趣。

有什麼建議?

這是返回IP地址列表的函數。

Function getIP() As String 

    Dim ips As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName) 

    For Each ip In ips.AddressList 
     If (ip.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork) Then 
      MessageBox.Show(ip.ToString) 
      Return ip.ToString 
     End If 
    Next 
    Return Nothing 

End Function 
+0

你有怎樣的任何代碼你收到他們並操縱他們,我們可以看看? – Kat

回答

1

不是通過IPHostEntry獲取IP地址相反,你可以通過網絡適配器枚舉,然後從每個適配器獲得IP地址。

A NetworkInterface通過NetworkInterfaceType屬性提供了它的類型。對於以太網適配器,這返回Ethernet。對於無線適配器,文檔沒有指定,但它爲我返回Wireless80211

示例代碼:

Imports System.Net.NetworkInformation 


Public Class Sample 

    Function GetIP() As String 
     Dim networkInterfaces() As NetworkInterface 


     networkInterfaces = NetworkInterface.GetAllNetworkInterfaces() 

     For Each networkInterface In networkInterfaces 
      If networkInterface.NetworkInterfaceType = NetworkInterfaceType.Ethernet Then 
       For Each address In networkInterface.GetIPProperties().UnicastAddresses 
        If address.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then 
         Return address.Address.ToString() 
        End If 
       Next address 
      End If 
     Next networkInterface 

     Return Nothing 
    End Function 

End Class 

或者,如果你想有一個稍微更簡潔的版本,你可以使用LINQ(相當於上面的代碼):

Function GetIP() As String 
    Return (
     From networkInterface In networkInterface.GetAllNetworkInterfaces() 
     Where networkInterface.NetworkInterfaceType = NetworkInterfaceType.Ethernet 
     From address In networkInterface.GetIPProperties().UnicastAddresses 
     Where address.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork 
     Select ip = address.Address.ToString() 
    ).FirstOrDefault() 
End Function  
+0

優秀! 這正是我想要的.. 非常感謝ConstantCoder !!! :) :) – Amey

相關問題