vb.netwinformsnetwork-programmingnic

Get current NIC settings


So, cutting a long story short the section of my code that I am currently unable to figure out is designed to report the current IP settings of a given NIC, so I want it to essentially spit out the IP, Subnet and default Gateway that it is currently set to. I have a solution working but it only seems to play nice when the NIC is set to DHCP which is not good for my application.

Here is my current code:

Public Sub NetGet()
    MainForm.NetLabelIP.Text = "IPv4 Address: "
    MainForm.NetLabelIP.Text = "subnet Mask: "
    MainForm.NetLabelIP.Text = "Default Gateway: "

    MainForm.NetLabelCN.Text = "Computer Name: " + System.Net.Dns.GetHostName()

    For Each ip In System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList
        If ip.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
            'IPv4 Adress
            MainForm.NetLabelIP.Text = "IPv4 Address: " + ip.ToString()

            For Each adapter As Net.NetworkInformation.NetworkInterface In Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()
                If adapter.Name = MainForm.interfaceSelector.SelectedItem Then
                    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
                                MainForm.NetLabelSM.Text = "Subnet Mask: " + unicastIPAddressInformation.IPv4Mask.ToString()

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

                                If unicastIPAddressInformation.PrefixOrigin = 3 Then
                                    DHCP = True
                                    MainForm.NetLabelDHCP.Text = "DHCP Enabled: TRUE"
                                Else
                                    DHCP = False
                                    MainForm.NetLabelDHCP.Text = "DHCP Enabled: FALSE"
                                End If

                                ''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
                End If
            Next
        End If
    Next
End Sub

I'm assuming it's going to be something abhorrently daft in hindsight, however I feel it best to share my request with the community so that anyone else looking for a similar solution can find their answers here.

Thanks in advance, guys.


Solution

  • This NetInterfacesInfo class implements two static (shared) methods the return informations on the Network Interfaces of a Machine:

    1. NetInterfacesInfo.GetNetworkInterfaces()

    This method returns all the Network Interfaces that support IPV4 except the Loopback interface.
    The informations are returned in a List(Of NetWorkInterfacesInfo), which exposes these properties:

    The IPV4Addresses property return a simplified list of the IP Addresses associated with the Network Interface. These informations are contained in a IpV4AddressInfo class, which provides these properties:

    Sample usage:

    Dim allNicsInfo = NetInterfacesInfo.GetNetworkInterfaces()
    For Each nic As NetInterfacesInfo.NetWorkInterfacesInfo In allNicsInfo
        Console.WriteLine($"Description: {nic.Description} Type: {nic.InterfaceType}")
    Next
    
    Dim Wireless = allNicsInfo.Where(Function(nic) nic.InterfaceType = NetworkInterfaceType.Wireless80211)
    

    1. NetInterfacesInfo.IpV4AddressSimpleList

    The simplified list of IP Addresses associated with a Network Interface can also be retrieved using this static (shared) method, providing the Name (actually, the Description property) of a Network Interface.
    This method returns a List(Of IpV4AddressInfo), a simplified, string only version, of each IP Address (of the specified Network Interface), its NetMask and the associated Default Gateway.

    Sample usage:

    Dim nicInfo = NetInterfacesInfo.IpV4AddressSimpleList("Some NIC Name")
    
    For Each ipV4Addr As NetInterfacesInfo.IpV4AddressInfo In nicInfo
        Console.WriteLine(ipV4Addr.IpAddress)
        Console.WriteLine(ipV4Addr.NetMask)
        Console.WriteLine(ipV4Addr.DefaultGateway)
    Next
    

    Attach the main class to a ComboBox:

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim allNicsInfo = NetInterfacesInfo.GetNetworkInterfaces()
        ComboBox1.DisplayMember = "ConnectionName"
        ComboBox1.DataSource = allNicsInfo
    End Sub
    
    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
        Dim cbo = DirectCast(sender, ComboBox)
        If cbo.SelectedIndex = -1 Then Return
        Dim nicInfo = DirectCast(cbo.SelectedItem, NetInterfacesInfo.NetWorkInterfacesInfo)
        TextBox1.Text = String.Join(Environment.NewLine, nicInfo.IPV4Addresses.
                        Select(Function(nic) $"IP Address: {nic.IpAddress} NetMask: {nic.NetMask}"))
        TextBox2.Text = nicInfo.IPV4Addresses.First().DefaultGateway
    End Sub
    


    Imports System.Linq
    Imports System.Net
    Imports System.Net.NetworkInformation
    Imports System.Net.Sockets
    
    Public Class NetInterfacesInfo
    
        Public Shared Function GetNetworkInterfaces() As List(Of NetWorkInterfacesInfo)
            Dim ifInfo As New List(Of NetWorkInterfacesInfo)()
    
            ifInfo.AddRange(GetNetworInterfaces().
                Where(Function(nic) nic.NetworkInterfaceType <> NetworkInterfaceType.Loopback AndAlso
                                    nic.Supports(NetworkInterfaceComponent.IPv4)).
                Select(Function(nic) New NetWorkInterfacesInfo() With {
                    .Description = nic.Description,
                    .ConnectionName = nic.Name,
                    .IsDHCPEnabled = nic.GetIPProperties().GetIPv4Properties().IsDhcpEnabled,
                    .DHCPSservers = nic.GetIPProperties().DhcpServerAddresses.ToList(),
                    .DnsServers = nic.GetIPProperties().DnsAddresses.ToList(),
                    .Gateways = nic.GetIPProperties().GatewayAddresses.Select(Function(ipa) ipa.Address).ToList(),
                    .InterfaceType = nic.NetworkInterfaceType,
                    .IpAddresses = nic.GetIPProperties().UnicastAddresses.Select(Function(ipa) ipa.Address).ToList(),
                    .MacAddress = nic.GetPhysicalAddress().GetAddressBytes().
                                  Select(Function(b) b.ToString("X")).Aggregate(Function(s1, s2) s2 + ":" + s1),
                    .Status = nic.OperationalStatus,
                    .IPV4Addresses = GetIpV4AddressInfo(nic)
                }))
            Return ifInfo
        End Function
    
    Public Shared Function IpV4AddressSimpleList(nicName As String) As List(Of IpV4AddressInfo)
        Dim nic = GetNetworInterfaceByName(nicName)
        If nic Is Nothing Then Return Nothing
        Return nic.GetIPProperties().UnicastAddresses.
                Where(Function(ipa) ipa.Address.AddressFamily = AddressFamily.InterNetwork).
                Select(Function(ipa) New IpV4AddressInfo() With {
                    .IpAddress = ipa.Address?.ToString(),
                    .NetMask = ipa.IPv4Mask?.ToString(),
                    .IsDnsEligible = ipa.IsDnsEligible,
                    .DefaultGateway = nic.GetIPProperties().GatewayAddresses.FirstOrDefault()?.Address?.ToString()
                }).ToList()
    End Function
    
    Private Shared Function GetIpV4AddressInfo(nic As NetworkInterface) As List(Of IpV4AddressInfo)
        Return nic.GetIPProperties().UnicastAddresses.
                Where(Function(ipa) ipa.Address.AddressFamily = AddressFamily.InterNetwork).
                Select(Function(ipa) New IpV4AddressInfo() With {
                    .IpAddress = ipa.Address?.ToString(),
                    .NetMask = ipa.IPv4Mask?.ToString(),
                    .IsDnsEligible = ipa.IsDnsEligible,
                    .DefaultGateway = nic.GetIPProperties().GatewayAddresses.FirstOrDefault()?.Address?.ToString()
                }).ToList()
    End Function
    
        Private Shared Function GetNetworInterfaces() As NetworkInterface()
            Return NetworkInterface.GetAllNetworkInterfaces()
        End Function
    
        Private Shared Function GetNetworInterfaceByName(nicName As String) As NetworkInterface
            Return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(Function(nic) nic.Name = nicName)
        End Function
    
        Public Class NetWorkInterfacesInfo
            Public Property ConnectionName As String
            Public Property Description As String
            Public Property IPV4Addresses As List(Of IpV4AddressInfo)
            Public Property IpAddresses As List(Of IPAddress)
            Public Property DHCPSservers As List(Of IPAddress)
            Public Property DnsServers As List(Of IPAddress)
            Public Property Gateways As List(Of IPAddress)
            Public Property IsDHCPEnabled As Boolean
            Public Property MacAddress As String
            Public Property Status As OperationalStatus
            Public Property InterfaceType As NetworkInterfaceType
        End Class
    
        Public Class IpV4AddressInfo
            Public Property IpAddress As String
            Public Property NetMask As String
            Public Property DefaultGateway As String
            Public Property IsDnsEligible As Boolean
        End Class
    
    End Class