使用VB.Net获取IP地址,子网,默认网关,DNS1和DNS2

时间:2016-11-26 02:50:43

标签: vb.net

我想单击一个按钮,使用网络堆栈信息更新多个文本标签或多个文本框。这是我追求的逻辑。

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。

1 个答案:

答案 0 :(得分:2)

您应该使用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