Digging into Network Adapters with Visual Basic.NET and VBScript using WMI

This article explains how you can retrieve network adapter information using both Visual Basic.NET and VB Script together with WMI.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 9
April 17, 2006
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

A downloadable file for this article is available here.

The sample downloadable solution (zip) is entirely developed using Visual Studio.NET 2003 Enterprise Architect on Windows Server 2003 Standard Edition.  But I am confident that it would work with other versions of Windows (which support .NET 1.1) as well.  To work with Visual Studio 2005, the coding may need minor modifications (I didn't really test it yet).  If you come across any problems, please do post them in the discussion, so that I can guide you accordingly.

If you wanted to use WMI with JavaScript (on the client side using IE), you may need to regularly check www.devarticles.com for a contribution dealing with this topic.

Some global routines used for my WMI development

I already contributed several articles on WMI with Visual Basic.NET and VB Script. I'm trying to cover almost all of the latest aspects of WMI.  I strongly suggest you go through my series on "WMI Programming with Visual Basic.NET" before reading this article.  The series even covers "event handling" using WMI with Visual Basic .NET in the form of a Windows service.

For flexibility in retrieving WMI information (using VB.NET), I frequently used the following simple global routines which help me to work with other areas of development very easily.

Public Sub addRow(ByRef dt As DataTable, ByVal p As String, ByVal v As String)
        Dim dr As DataRow
        dr = dt.NewRow
        dr("Property") = p
        dr("Value") = v
        dt.Rows.Add(dr)
    End Sub
Public Function getStructure() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add(New DataColumn("Property"))
        dt.Columns.Add(New DataColumn("Value"))
        Return dt
    End Function

Two of my global routines are the above ones, "getStructure" and "addRow."  Both are generally used if I have a "Property->value" scenario. "GetStructure" just creates a data table structure and "AddRow" simply adds a data row for every data table passed to it. 

Listing network adapter information using WMI

How do you list all of the network adapters available on your system?  We'll assume that you also want a list of all bridges and other logical network connections as well.

Before going to the WMI code, we need to define the cache to store that information.  The following are the two routines I declared in "globals.vb" to hold the cache of information.

Public Function getNetworkAdapterStructure() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add(New DataColumn("AdapterType"))
        dt.Columns.Add(New DataColumn("MACAddress"))
        dt.Columns.Add(New DataColumn("Manufacturer"))
        Return dt
    End Function
 
    Public Sub addNetworkAdapterRow(ByRef dt As DataTable, ByVal
AdapterType As String, ByVal MACAddress As String, ByVal
Manufacturer As String)
        Dim dr As DataRow
        dr = dt.NewRow
        dr("AdapterType") = AdapterType
        dr("MACAddress") = MACAddress
        dr("Manufacturer") = Manufacturer
        dt.Rows.Add(dr)
    End Sub

The following is the WMI code to retrieve our desired information.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
        Try
            Dim searcher As New ManagementObjectSearcher( _
                "rootCIMV2", _
                "SELECT * FROM Win32_NetworkAdapter")
            Dim dt As DataTable =
globals.getNetworkAdapterStructure
            For Each queryObj As ManagementObject In searcher.Get
()
                globals.addNetworkAdapterRow(dt, queryObj
("AdapterType"), queryObj("MACAddress"), queryObj
("Manufacturer"))
            Next
            Me.DataGrid1.DataSource = dt
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for
WMI data: " & err.Message)
        End Try
    End Sub

I excluded some of the properties (as it would make the program too long) from the existing WMI class (Win32_NetworkAdapter) to give you only the most important ones.  The above program would list the MACAddress, Manufacturer and AdapterType. You can further extend the above program with several other properties available in the "Win32_NetworkAdapter" class.  You can even refer to MSDN online for further properties.

You can achieve the same thing with VBScript using the following code:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer &
"rootCIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapter",,48)
For Each objItem in colItems
    Wscript.Echo "AdapterType: " & objItem.AdapterType
    Wscript.Echo "MACAddress: " & objItem.MACAddress
    Wscript.Echo "Manufacturer: " & objItem.Manufacturer
Next

Listing extended information about network adapters using WMI

In the previous section, we only displayed preliminary information.  The users may need further extended information like IP address, DHCP information, and so on from network adapters using WMI.  Let us see how to get it using VB.NET:

Try
            Dim searcher As New ManagementObjectSearcher( _
                "rootCIMV2", _
                "SELECT * FROM
Win32_NetworkAdapterConfiguration")
            For Each queryObj As ManagementObject In searcher.Get
()
                Me.TextBox1.Text &= "Caption: " + queryObj
("Caption") & ControlChars.NewLine
                Me.TextBox1.Text &= "DHCPEnabled: " + (queryObj
("DHCPEnabled").ToString) & ControlChars.NewLine
                Me.TextBox1.Text &= "DHCPServer: " + queryObj
("DHCPServer") & ControlChars.NewLine
                Me.TextBox1.Text &= "DNSDomain: " + queryObj
("DNSDomain") & ControlChars.NewLine
                Me.TextBox1.Text &= "DNSHostName: " + queryObj
("DNSHostName") & ControlChars.NewLine
 
                If queryObj("IPAddress") Is Nothing Then
                    Me.TextBox1.Text &= "IPAddress: " + queryObj
("IPAddress") & ControlChars.NewLine
                Else
                    Dim arrIPAddress As String()
                    arrIPAddress = queryObj("IPAddress")
                    For Each arrValue As String In arrIPAddress
                        Me.TextBox1.Text &= "IPAddress: {0}" +
arrValue & ControlChars.NewLine
                    Next
                End If
 
                If queryObj("IPSubnet") Is Nothing Then
                    Me.TextBox1.Text &= "IPSubnet: " + queryObj
("IPSubnet") & ControlChars.NewLine
                Else
                    Dim arrIPSubnet As String()
                    arrIPSubnet = queryObj("IPSubnet")
                    For Each arrValue As String In arrIPSubnet
                        Me.TextBox1.Text &= "IPSubnet: {0}" +
arrValue & ControlChars.NewLine
                    Next
                End If
                Me.TextBox1.Text &= "MACAddress: {0}" + queryObj
("MACAddress") & ControlChars.NewLine
                Me.TextBox1.Text &=
"======================================" & ControlChars.NewLine
            Next
 
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for
WMI data: " & err.Message)
        End Try

I excluded some of the properties (as it would make the program too long) from the existing WMI class (Win32_NetworkAdapterConfiguration) to give you only the most important ones.  The above program would list the Caption, status of DHCP, DHCP Server IP if available, DNS info, IP address of the adapter and so on. You can further extend the above program with several other properties available in the "Win32_NetworkAdapterConfiguration" class.  You can even refer to MSDN online for further properties.

You can achieve the same thing with VB Script by using the following code:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer &
"rootCIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkAdapterConfiguration",,48)
For Each objItem in colItems
    Wscript.Echo "Caption: " & objItem.Caption
    Wscript.Echo "DHCPEnabled: " & objItem.DHCPEnabled
    Wscript.Echo "DHCPServer: " & objItem.DHCPServer
    Wscript.Echo "DNSDomain: " & objItem.DNSDomain
    Wscript.Echo "DNSHostName: " & objItem.DNSHostName
    If isNull(objItem.IPAddress) Then
        Wscript.Echo "IPAddress: "
    Else
        Wscript.Echo "IPAddress: " & Join(objItem.IPAddress, ",")
    End If
    If isNull(objItem.IPSubnet) Then
        Wscript.Echo "IPSubnet: "
    Else
        Wscript.Echo "IPSubnet: " & Join(objItem.IPSubnet, ",")
    End If
    Wscript.Echo "MACAddress: " & objItem.MACAddress
Next

Listing network connection information using WMI

Before going into the WMI code, we need to define the cache to store that information.  The following are the two routines I declared in "globals.vb" to hold the cache of information.

Public Function getNetworkConnectionStructure() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add(New DataColumn("Caption"))
        dt.Columns.Add(New DataColumn("ConnectionState"))
        dt.Columns.Add(New DataColumn("ConnectionType"))
        dt.Columns.Add(New DataColumn("Description"))
        dt.Columns.Add(New DataColumn("Name"))
        dt.Columns.Add(New DataColumn("RemoteName"))
        dt.Columns.Add(New DataColumn("RemotePath"))
        Return dt
    End Function
 
    Public Sub addNetworkConnectionRow(ByRef dt As DataTable,
ByVal Caption As String, ByVal ConnectionState As String, ByVal
ConnectionType As String, ByVal Description As String, ByVal Name
As String, ByVal RemoteName As String, ByVal RemotePath As
String)
        Dim dr As DataRow
        dr = dt.NewRow
        dr("Caption") = Caption
        dr("ConnectionState") = ConnectionState
        dr("ConnectionType") = ConnectionType
        dr("Description") = Description
        dr("Name") = Name
        dr("RemoteName") = RemoteName
        dr("RemotePath") = RemotePath
        dt.Rows.Add(dr)
    End Sub

The following is the WMI code, to retrieve our desired information.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
        Try
            Dim searcher As New ManagementObjectSearcher( _
    "rootCIMV2", _
    "SELECT * FROM Win32_NetworkConnection")
            Dim dt As DataTable =
globals.getNetworkConnectionStructure
            For Each queryObj As ManagementObject In searcher.Get
()
                globals.addNetworkConnectionRow(dt, queryObj
("Caption"), queryObj("ConnectionState"), queryObj
("ConnectionType"), queryObj("Description"), queryObj("Name"),
queryObj("RemoteName"), queryObj("RemotePath"))
            Next
            Me.DataGrid1.DataSource = dt
        Catch err As ManagementException
            MessageBox.Show("An error occurred while querying for
WMI data: " & err.Message)
        End Try
    End Sub

I excluded some of the properties (as it would make the program too long) from the existing WMI class (Win32_NetworkConnection) to give you only the most important ones.  The above program would list  the Caption, State of Connection, Type of Connection, Remote Name, Remote Path, and so on. You can further extend the above program with several other properties available in the "Win32_NetworkConnection" class.  You can even refer to MSDN online for further properties.

You can achieve the same thing with VB Script with the following code:

strComputer = "."
Set objWMIService = GetObject("winmgmts:" & strComputer &
"rootCIMV2")
Set colItems = objWMIService.ExecQuery( _
    "SELECT * FROM Win32_NetworkConnection",,48)
For Each objItem in colItems
    Wscript.Echo "Caption: " & objItem.Caption
    Wscript.Echo "ConnectionState: " & objItem.ConnectionState
    Wscript.Echo "ConnectionType: " & objItem.ConnectionType
    Wscript.Echo "Description: " & objItem.Description
    Wscript.Echo "Name: " & objItem.Name
    Wscript.Echo "RemoteName: " & objItem.RemoteName
    Wscript.Echo "RemotePath: " & objItem.RemotePath
Next

Summary

You can further delve into the classes of WMI and design your own application to retrieve almost every important aspect of network adapters.  If you extend your skills to ASP.NET, then you can develop a web application which can retrieve your network information on the fly, without your presence in the office itself!  I think you can imagine a similar application at the Pocket PC level!  Good luck.

If you need articles on any particular topic of WMI, do not hesitate to post in the discussion.  I shall definitely help you out. 

Any comments, suggestions, bugs, errors, feedback etc. are highly appreciated at jag_chat@yahoo.com.

blog comments powered by Disqus
VISUAL BASIC.NET ARTICLES

- Basic Form Properties and Modality in VB.NET
- Multiple Document Interfaces in Visual Basic
- Visual Basic for Beginners
- ASP.NET Image to PDF with VB.Net
- MySQL in ASP.NET: Mono using VB.NET
- AsyncFileUpload File Type and File Size Vali...
- Visual Studio: Adding Functionality and Style
- Clocks and Countdowns
- User-defined Functions using Visual Basic Ap...
- Understanding Object Binding in VBA
- Mastering the Message Box
- Testing a Windows Forms Application
- Using Visual Basic.NET Features to Code a Wi...
- Correcting Code in a Windows Forms Applicati...
- Write Readable Code and Comments for Windows...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 8 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials