Visual Basic WMI Network Services
Obtaining Network Adapter Configuration using WMI
     
Posted:   Monday March 04, 2002
Updated:   Monday November 28, 2011
     
Applies to:   VB5, VB6
Developed with:   VB6, Windows XP
OS restrictions:   Windows NT, 2000, XP. See Prerequisites below.
Author:   VBnet - Randy Birch
     

Related:  

Win32_NetworkAdapter: WMI Network Adapter Info
Win32_NetworkAdapterConfiguration: WMI Network Adapter Configuration

     
 Prerequisites
Windows Script Host is built into Microsoft Windows 98, 2000, ME and XP. If you are running Windows 95 or NT4, you can download Windows Script Host from the Microsoft Windows Script Technologies Web site at http://msdn.microsoft.com/scripting/. Some information is not returned on non-NT-based systems.

A reference set in Projects / References to the Microsoft WMI Scripting Library.


Windows Management Instrumentation (WMI), a kernel-level instrumentation technology for the Microsoft® Windows® platform. WMI provides the basis for hardware instrumentation in future Windows environments. Close coupling of WMI with services developed to conform to the Web-Based Enterprise Management (WBEM) initiative will allow Microsoft to simplify instrumentation and provide consistent, open access to management data.

Both WMI and WBEM are key components in Microsoft's manageability and total cost of ownership containment efforts. WMI is integrated into both the Windows® 98 and Windows® 2000 kernel to provide driver data and events. WMI is an extensible design, and an original equipment manufacturer (OEM) or independent hardware vendor (IHV) can extend the instrumented data set.

WMI publishes information, configures device settings, and supplies event notification from device drivers. WMI is part of the Win32® Driver Model (WDM) architecture. However, it has broad utility and can be used with other types of drivers as well (such as SCSI and NDIS).  WMI also allows a management application to configure a device, which may need to do this because of some driver-raised event or because of the data collected by the management application.

The VBnet WMI demos will show how retrieve various system settings often not available without third-party DLLs, or intricate API calls.

This demo shows how to retrieve network adapter information for all installed and running network provider services, including network adapters and mini-ports loaded within the context of the operating system or user. The actual code is contained in the wmiNetAdapterConfig routine; the majority of the code below supports extracting the DHCP Lease date and time information from the values returned by WMI. 

This demo and illustration only show some of the available information from the class. For a complete listing see the table in the Comments section below. Note that some systems may not return information in all class properties.

 BAS Module Code
None.

 Form Code
To a form add a command button (Command1) and a listview (Listview1). Set a reference in Projects / References to the Microsoft WMI Scripting Library, and add the following to the form:

Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'/* Below used for listview column auto-resizing
Private Const LVM_FIRST As Long = &H1000
Private Const LVM_SETCOLUMNWIDTH As Long = (LVM_FIRST + 30)
Private Const LVSCW_AUTOSIZE As Long = -1
Private Const LVSCW_AUTOSIZE_USEHEADER As Long = -2

Private Declare Function SendMessage Lib "user32" _
   Alias "SendMessageA" _
  (ByVal hwnd As Long, _
   ByVal wMsg As Long, _
   ByVal wParam As Long, _
   lParam As Any) As Long


Private Sub Form_Load()

   With ListView1
      .ListItems.Clear
      .ColumnHeaders.Clear
      .ColumnHeaders.Add , , "NIC"
      .ColumnHeaders.Add , , "MAC"
      .ColumnHeaders.Add , , "IP Addr"
      .ColumnHeaders.Add , , "DHCP Svr"
      .ColumnHeaders.Add , , "LeaseObt"
      .ColumnHeaders.Add , , "LeaseExp"
      .ColumnHeaders.Add , , "WINS"
      .ColumnHeaders.Add , , "Host"
      .ColumnHeaders.Add , , "Domain"
      .ColumnHeaders.Add , , "NIC Name"
      .View = lvwReport
      .Sorted = False
   End With
     
   Command1.Caption = "Get Adapter Config"

End Sub


Private Sub Command1_Click()

   ListView1.ListItems.Clear
   Call wmiNetAdapterConfig
   Call lvAutosizeControl(ListView1)
   
End Sub


Private Sub lvAutosizeControl(lv As ListView)

   Dim col2adjust As Long

  '/* Size each column based on the maximum of
  '/* EITHER the columnheader text width, or,
  '/* if the items below it are wider, the
  '/* widest list item in the column
   For col2adjust = 0 To lv.ColumnHeaders.Count - 1
   
      Call SendMessage(lv.hwnd, _
                       LVM_SETCOLUMNWIDTH, _
                       col2adjust, _
                       ByVal LVSCW_AUTOSIZE_USEHEADER)

   Next
   
End Sub


Private Function SplitDateTimeBias(ByVal leasedate As String, _
                                   leasedatepart As String, _
                                   leasetimepart As String) As Long

  'takes a datetime returned by the
  'Win32_NetworkAdapterConfiguration
  'and splits out the date and time
  'components, returns them in the
  'leasedatepart and leasetimepart
  'passed variables, and returns the
  'bias to be applied to the resultant date.
   Dim pos     As Long
   Dim bias    As Long
  
   pos = InStr(leasedate, ".")

   If pos > 0 Then

      bias = StripTimeZoneBias(leasedate)
      leasedatepart = Left$(leasedate, 8)
      leasetimepart = Mid$(leasedate, 9, pos - Len(leasedatepart) - 1)
      leasedatepart = InsertInString(leasedatepart, "-", 5, "")
      leasedatepart = InsertInString(leasedatepart, "-", 8, "")
      leasetimepart = InsertInString(leasetimepart, ":", 3, "")
      leasetimepart = InsertInString(leasetimepart, ":", 6, "")
      
      SplitDateTimeBias = bias

   Else

   End If

End Function


Private Function InsertInString(ByVal sOriginal As String, _
                                sReplace As String, _
                                nField As Long, _
                                sDelimeter As String) As String
    
   'c 1998 Mario Lavignasse
   'Abbott Scientific
   'Replaces or inserts a string into a (any char) delimeted string
   '
   'Syntax:
   'sOriginal:  string of interest, returned unchanged
   'sReplace:   replacement or insert chr(s)
   'nField:     1-based position for the insert/replace to begin
   'sDelimeter: string to insert/replace. If empty, sReplace is
   '            inserted, if present sDelimeter is replaced by sReplace.
   '
   'Examples:
   'Inserting:
   ' x = InsertInString("Hello World", "Hello ", 7, "")
   '  (x="Hello Hello World")
   '
   'Replacing:
   ' x = InsertInString("Hello World", "Hello ", 7, "World")
   '   (x="Hello Hello")
         
   Dim nCount As Long
   Dim nStart As Long
   Dim nLast As Long
    
   Do While InStr(nStart + 1, sOriginal, sDelimeter) > 0
    
      nStart = InStr(nStart + 1, sOriginal, sDelimeter)
      nCount = nCount + 1
      
      If nCount >= nField Then
         Exit Do
      End If
      
      nLast = nStart
        
   Loop
    
   
   Select Case nCount
   
      Case 1
         InsertInString = sReplace & Mid$(sOriginal, nStart)
      
      Case Is >= nField
         InsertInString = Mid$(sOriginal, 1, nLast) & _
                               sReplace & Mid$(sOriginal, nStart)
      Case Else
         InsertInString = sOriginal & _
                          String$((nField - 1) - nCount, sDelimeter) & _
                          sReplace
   End Select
    
End Function


Private Function StripTimeZoneBias(leasedate As String) As Long

   Dim pos As Long
   Dim tmp As String
   
   pos = InStr(leasedate, "-")
   
   If pos = 0 Then
      
      pos = InStr(leasedate, "+")
      
      If pos = 0 Then
         StripTimeZoneBias = 0
      Else
      
      End If
      
   Else
   
      tmp = Mid$(leasedate, pos, Len(leasedate))
      leasedate = Mid$(leasedate, 1, pos - 1)
      StripTimeZoneBias = CLng(tmp)
      
   End If

End Function


Private Sub wmiNetAdapterConfig()

   Dim nicSet As SWbemObjectSet
   Dim nic As SWbemObject
   
  'working vars for the lease date/times and listview
   Dim dtb As String
   Dim d As String
   Dim t As String
   Dim bias As Long
   Dim itmx As ListItem
   
  'must have error handler enabled, as all
  'adapters do not return all information
   On Local Error Resume Next
   
   Set nicSet = GetObject("winmgmts:{impersonationLevel=impersonate}"). _
                           InstancesOf("Win32_NetworkAdapterConfiguration")   
   
   For Each nic In nicSet
   
      Set itmx = ListView1.ListItems.Add(, , nic.Index)
      
      itmx.SubItems(1) = nic.MACAddress
      
      If nic.IPEnabled Then
         itmx.SubItems(2) = nic.IPAddress(0)
      End If
          

      If nic.DHCPEnabled Then

         itmx.SubItems(3) = nic.DHCPServer
      
        'if DHCPLeaseObtained is not null,
        'call a method to extract the date,
        'time and bias (dtb) from the lease date
        'and show the results (time not shown)
         If Not IsNull(nic.DHCPLeaseObtained) Then
            dtb = nic.DHCPLeaseObtained
            bias = SplitDateTimeBias(dtb, d, t)
            itmx.SubItems(4) = Format$(d, "short date")
         End If
          
        'same again
         If Not IsNull(nic.DHCPLeaseExpires) Then
            dtb = nic.DHCPLeaseExpires
            bias = SplitDateTimeBias(dtb, d, t)
            itmx.SubItems(5) = Format$(d, "short date")
         End If
      
      End If

      itmx.SubItems(6) = nic.DNSEnabledForWINSResolution
      itmx.SubItems(7) = nic.DNSHostName
      itmx.SubItems(8) = nic.DNSDomain      
      itmx.SubItems(9) = nic.Description
      
   Next

End Sub
 Comments
All information returned in the Win32_NetworkAdapterConfiguration class (note that some systems may not return information in all class properties):
   
boolean ArpAlwaysSourceRoute
boolean ArpUseEtherSNAP
string Caption
string DatabasePath
boolean DeadGWDetectEnabled
string DefaultIPGateway[]
uint8 DefaultTOS
uint8 DefaultTTL
string Description
boolean DHCPEnabled
datetime DHCPLeaseExpires
datetime DHCPLeaseObtained
string DHCPServer
string DNSDomain
string DNSDomainSuffixSearchOrder[]
boolean DNSEnabledForWINSResolution
string DNSHostName
string DNSServerSearchOrder[]
boolean DomainDNSRegistrationEnabled
uint32 ForwardBufferMemory
boolean FullDNSRegistrationEnabled
uint16 GatewayCostMetric[]
uint8 IGMPLevel
uint32 Index
string IPAddress[]
uint32 IPConnectionMetric
boolean IPEnabled
boolean IPFilterSecurityEnabled
boolean IPPortSecurityEnabled
string IPSecPermitIPProtocols[]
string IPSecPermitTCPPorts[]
string IPSecPermitUDPPorts[]
string IPSubnet[]
boolean IPUseZeroBroadcast
string IPXAddress
boolean IPXEnabled
uint32 IPXFrameType[]
uint32 IPXMediaType
string IPXNetworkNumber[]
string IPXVirtualNetNumber
uint32 KeepAliveInterval
uint32 KeepAliveTime
string MACAddress
uint32 MTU
uint32 NumForwardPackets
boolean PMTUBHDetectEnabled
boolean PMTUDiscoveryEnabled
string ServiceName
string SettingID
uint32 TcpipNetbiosOptions
uint32 TcpMaxConnectRetransmissions
uint32 TcpMaxDataRetransmissions
uint32 TcpNumConnections
boolean TcpUseRFC1122UrgentPointer
uint16 TcpWindowSize
boolean WINSEnableLMHostsLookup
string WINSHostLookupFile
string WINSPrimaryServer
string WINSScopeID
string WINSSecondaryServer

 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright ©1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter