2016-11-26 107 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