2016-11-26 158 views
1

我想單擊一個按鈕,使用網絡堆棧信息更新多個文本標籤或多個文本框。這是我追求的邏輯。使用VB.Net獲取IP地址,子網,默認網關,DNS1和DNS2

Button2 event 
Label1.text = Computer Name 
Label2.text = IP Address 
Label3.text = Subnet Mask 
Label4.text = Default Gateway 
Label5.text = DNS1 
Label6.text = DNS2 

我有一些工作代碼

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click 

    Dim strHostName As String 

    Dim strIPAddress As String 


    strHostName = System.Net.Dns.GetHostName() 

    strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString() 



    TextBox2.Text = strIPAddress 
    Lable_IPAddress.Text = strIPAddress 


End Sub 

我不知道如何得到默認網關或DNS的。子網掩碼對於我想要做的事情並不重要,但是網關和DNS條目非常重要。

我只想點擊一個按鈕,讓它顯示一個格式良好的網絡堆棧。這似乎不應該那麼辛苦,但我還不熟悉vb.net。

回答

0

您應該使用NetworkInterface類。它包含你想要的所有信息。你可以在這裏獲得詳細信息:

https://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkinterface(v=vs.110).aspx

簡單的用法:

'Computer Name 
Label1.Text = System.Net.Dns.GetHostName() 
For Each ip In System.Net.Dns.GetHostEntry(Label1.Text).AddressList 
    If ip.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then 
     'IPv4 Adress 
     Label2.Text = ip.ToString() 

     For Each adapter As Net.NetworkInformation.NetworkInterface In Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() 
      For Each unicastIPAddressInformation As Net.NetworkInformation.UnicastIPAddressInformation In adapter.GetIPProperties().UnicastAddresses 
       If unicastIPAddressInformation.Address.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then 
        If ip.Equals(unicastIPAddressInformation.Address) Then 
         'Subnet Mask 
         Label3.Text = unicastIPAddressInformation.IPv4Mask.ToString() 

         Dim adapterProperties As Net.NetworkInformation.IPInterfaceProperties = adapter.GetIPProperties() 
         For Each gateway As Net.NetworkInformation.GatewayIPAddressInformation In adapterProperties.GatewayAddresses 
          'Default Gateway 
          Label4.Text = gateway.Address.ToString() 
         Next 

         'DNS1 
         If adapterProperties.DnsAddresses.Count > 0 Then 
          Label5.Text = adapterProperties.DnsAddresses(0).ToString() 
         End If 

         'DNS2 
         If adapterProperties.DnsAddresses.Count > 1 Then 
          Label6.Text = adapterProperties.DnsAddresses(1).ToString() 
         End If 
        End If 
       End If 
      Next 
     Next 
    End If 
Next 
+0

這完美地工作。謝謝。我一直在嘗試各種不同的東西,我發現的所有教程和其他東西都不是我正在尋找的東西,或者正在使用組合框之類的東西以及沒有翻譯成我想要的東西使用這些信息。我只是想點擊一個按鈕,讓它顯示網絡堆棧。你的代碼完美地工作,爲此目的。謝謝。 – user1837575