How to read IP Address of 'actually used' lan nic?

amorosik

Member
Local time
Today, 23:17
Joined
Apr 18, 2020
Messages
552
Normallly, using this code, ALL pc ip addresses are returned
But wanting to know exactly the address of the wired or wireless network card that pc is using, how to do?
I ask this beacuae if the pc has two lan ports on the motherboard, a wifi card, and a virtual lan like those installed by HyperV, the result of the function is almost nevere the adress expected

Code:
Function GetLanIpAddress() As String
    Const STR_COMPUTER As String = "."
    Dim objWMI As Object
    Dim colAdapters As Object
    Dim objAdapter As Object
    Dim sIp As String
    
    ' Avvia WMI
    Set objWMI = GetObject("winmgmts:\\" & STR_COMPUTER & "\root\cimv2")
    ' Seleziona solo adattatori con IP abilitato e non wireless
    Set colAdapters = objWMI.ExecQuery( _
        "SELECT * FROM Win32_NetworkAdapterConfiguration " & _
        "WHERE IPEnabled = TRUE")
    
     For Each objAdapter In colAdapters
        If Not IsNull(objAdapter.IpAddress) Then
            Dim arrIP
            arrIP = objAdapter.IpAddress
            Debug.Print "IP ADDRESS = " & arrIP(i)
            End If
        Next
    
    For Each objAdapter In colAdapters
        If Not IsNull(objAdapter.IpAddress) Then
            'Dim arrIP
            arrIP = objAdapter.IpAddress
            Dim i As Integer
            For i = LBound(arrIP) To UBound(arrIP)
                ' Salta gli IPv6
                If InStr(arrIP(i), ":") = 0 Then
                    ' Se è un IP privato (LAN)
                    If Left(arrIP(i), 4) = "192." Or _
                       Left(arrIP(i), 4) = "10." Or _
                       Left(arrIP(i), 4) = "172." Then
                        GetLanIpAddress = arrIP(i)
                        Exit Function
                    End If
                End If
            Next i
        End If
    Next
    
    GetLanIpAddress = "" ' Nessun IP trovato
End Function
 
I see that now.

I used cmd window to output IPConfig info. I have 5 configurations and 4 are disconnected so I only get IP for my WiFi as only enabled objects are retrieved by the query into IPConfgSet. If I remove the filter criteria, I get 18 items. I also looked at DeviceManager and it lists 11 items under Network adapters.

I modified above code to get the IPConfig.Caption property (see complete list at https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-networkadapterconfiguration). The output is [00000013] Intel(R) Wireless-N 7260. That is definitely model of the adapter I installed last month. Perhaps you can use that property to identify the connection you want.

One curiosity this exercise revealed is the VBA (without filter criteria) lists a Qualcomm adapter that was replaced by the Intel adapter. The Qualcomm device is not listed in DeviceManager nor IPConfig cmd.
 
Last edited:
Can you describe the main purpose for determining the IP address? Perhaps if the goal was known, someone can offer an appropriate approach. I was thinking of maybe using an HTTP request to get this info.
 
When I had to do this (and at the time, didn't know about WMI), what I used was to shell a command to the CMD prompt:

Code:
ipconfig  > .\ipcfg.txt

Then I opened file ".\ipcfg.txt" (for reading) and did successive LINE INPUT statements looking for keywords. Most of the things were easy to recognize and most of the potential connections were "Not connected" and thus easy to disregard. If you do this once by hand, you can get all the keywords that you need in order to pick apart the inputs. This trick also works on MAC addresses using the ARP command. If you do this, remember to CLOSE and KILL the file when done with it.

Note that if you have a typical modern network I/F, the IPv4 address is your internal network's DHCP-assigned address, not the network IP, because the network IP will probably be for IPv6, and you might see several such addresses for different purposes.
 
Can you describe the main purpose for determining the IP address? Perhaps if the goal was known, someone can offer an appropriate approach. I was thinking of maybe using an HTTP request to get this info.

I want to log the communication channel used to be able to reproduce the environment used during the execution of some procedures, for example when there are performance problems or errors in communication
It happens that there are notebooks and maybe the customer says "... it is connected with the cable ..." while instead it is working via wifi and things of this type
And so my main goal is to understand, via code, what is the address of the nic inside the machine, which at this moment is connecting the computer to the rest of the network
 
I want to log the communication channel used to be able to reproduce the environment used during the execution of some procedures, for example when there are performance problems or errors in communication
It happens that there are notebooks and maybe the customer says "... it is connected with the cable ..." while instead it is working via wifi and things of this type
And so my main goal is to understand, via code, what is the address of the nic inside the machine, which at this moment is connecting the computer to the rest of the network
Perhaps you can get this information using PowerShell (by ChatGPT):
Code:
Write-Host "Equipo local: $env:COMPUTERNAME`n"

# Obtener adaptadores físicos que estén activos
$adapters = Get-NetAdapter -Physical | Where-Object { $_.Status -eq 'Up' }

foreach ($adapter in $adapters) {
    $name = $adapter.Name
    $interfaceDesc = $adapter.InterfaceDescription
    $status = $adapter.Status
    $ifIndex = $adapter.ifIndex

    # Determinar tipo de conexión
    $type = if ($interfaceDesc -match 'wireless|wi-?fi') { 'Wireless' } else { 'Ethernet' }

    # Obtener direcciones IP asociadas (IPv4 únicamente)
    $ipInfo = Get-NetIPAddress -InterfaceIndex $ifIndex -AddressFamily IPv4 -ErrorAction SilentlyContinue
    $ipList = $ipInfo | Select-Object -ExpandProperty IPAddress

    Write-Host "Adaptador: $name"
    Write-Host "  Tipo: $type"
    Write-Host "  Estado: $status"
    Write-Host "  IP(s): $($ipList -join ', ')`n"
}
 
you may use this function provided by ChatGPT:
Code:
Public Function ActiveAdapter() As String
'---------------------------------------------------------------------------------------
' Procedure : ActiveAdapter
' Author    : ChatGPT modified: bbfromgb
' Date      : 19.06.2025
' Purpose   : find network adapter having internet access
'             Uses route print 0.0.0.0 to determine which interface is being used to reach the Internet.
'             Matches the IP address from the route to an adapter in WMI.
'             Displays the adapter info: description, IP, MAC, and gateway.
'---------------------------------------------------------------------------------------
'
Dim line As String, parts As Variant, interfaceIP As String, IP As Variant, foundRoute As Boolean, foundAdapter As Boolean, i As Integer
Dim WMI As Object, shell As Object, exec As Object, configs As Object, config As Object


   On Error GoTo ActiveAdapter_Error

' Step 1: Get the interface IP used for default Internet route (0.0.0.0)
Set shell = CreateObject("WScript.Shell")
Set exec = shell.exec("cmd /c route print 0.0.0.0")

foundRoute = False

Do While Not exec.StdOut.AtEndOfStream
    line = Trim(exec.StdOut.ReadLine())
    If InStr(line, "0.0.0.0") = 1 Then
        parts = Split(line)
        If UBound(parts) >= 3 Then
            For i = UBound(parts) To 0 Step -1
              If InStr(parts(i), ".") Then Exit For
            Next i
            interfaceIP = parts(i)
            foundRoute = True
            Exit Do
        End If
    End If
Loop

If Not foundRoute Then
    Debug.Print "Could not find default Internet route."
    Exit Function
End If

Debug.Print "Interface used for Internet: " & interfaceIP
Debug.Print "-----------------------------------------"

' Step 2: Match that IP to a network adapter
Set WMI = GetObject("winmgmts:\\.\root\CIMV2")
Set configs = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")

foundAdapter = False

For Each config In configs
    If Not IsNull(config.IPAddress) Then
        For Each IP In config.IPAddress
            If IP = interfaceIP Then
                foundAdapter = True
                Debug.Print "Adapter with Internet access:"
                Debug.Print "  Description: " & config.Description
                Debug.Print "  MAC Address: " & config.MACAddress
                Debug.Print "  IP Address : " & IP
                If Not IsNull(config.DefaultIPGateway) Then
                    Debug.Print "  Gateway    : " & Join(config.DefaultIPGateway, ", ")
                End If
                Exit For
            End If
        Next
    End If
Next

If Not foundAdapter Then
    Debug.Print "No matching adapter found for Internet access."
End If
 

ActiveAdapter_Exit:
   Exit Function

ActiveAdapter_Error:
  Select Case Err.Number

  Case Else
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ActiveAdapter from module mdlInternet"
    Resume ActiveAdapter_Exit:
  End Select
End Function
 
I have structured and cleaned up the code of ChatGPT a bit. Seems to work in a first shot.

Code:
Public Type NIC
    Description As String
    MACAddress As String
    IPAddress As String
    DefaultGateway As String
End Type

Public Sub TestIt()
    Dim foundNIC As NIC
    foundNIC = MatchIPToNetworkAdapter(GetInterfaceIPUsedForDefaultInternetRoute())

    Debug.Print "Adapter with Internet access:"
    Debug.Print "  Description: " & foundNIC.Description
    Debug.Print "  MAC Address: " & foundNIC.MACAddress
    Debug.Print "  IP Address : " & foundNIC.IPAddress
    Debug.Print "  DefaultGateway : " & foundNIC.DefaultGateway
End Sub

Public Function GetInterfaceIPUsedForDefaultInternetRoute() As String
    With CreateObject("WScript.Shell").exec("cmd /c route print 0.0.0.0")
        Do While Not .StdOut.AtEndOfStream
            Dim line As String
            line = Trim(.StdOut.ReadLine())

            If InStr(line, "0.0.0.0") <> 0 Then
                Dim lineParts() As String
                lineParts = Split(line)

                If UBound(lineParts) >= 3 Then
                    Dim index As Long
                    For index = UBound(lineParts) To 0 Step -1
                        If InStr(lineParts(index), ".") Then Exit For
                    Next index

                    GetInterfaceIPUsedForDefaultInternetRoute = lineParts(index)

                    Exit Function
                End If
            End If
        Loop
    End With
End Function

Public Function MatchIPToNetworkAdapter(ByVal iPAddressToMatch As String) As NIC
    If Len(iPAddressToMatch) = 0 Then Exit Function

    Dim config As Object
    For Each config In GetObject("winmgmts:\\.\root\CIMV2") _
                       .ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")
        If Not IsNull(config.IPAddress) Then
            Dim item As Variant
            For Each item In config.IPAddress
                If item = iPAddressToMatch Then
                    MatchIPToNetworkAdapter.Description = config.Description
                    MatchIPToNetworkAdapter.MACAddress = config.MACAddress
                    MatchIPToNetworkAdapter.IPAddress = iPAddressToMatch

                    If Not IsNull(config.DefaultIPGateway) Then _
                        MatchIPToNetworkAdapter.DefaultGateway = Join(config.DefaultIPGateway, ", ")

                    Exit Function
                End If
            Next
        End If
    Next
End Function
 
you may use this function provided by ChatGPT:
Code:
Public Function ActiveAdapter() As String
'---------------------------------------------------------------------------------------
' Procedure : ActiveAdapter
' Author    : ChatGPT modified: bbfromgb
' Date      : 19.06.2025
' Purpose   : find network adapter having internet access
'             Uses route print 0.0.0.0 to determine which interface is being used to reach the Internet.
'             Matches the IP address from the route to an adapter in WMI.
'             Displays the adapter info: description, IP, MAC, and gateway.
'---------------------------------------------------------------------------------------
'
Dim line As String, parts As Variant, interfaceIP As String, IP As Variant, foundRoute As Boolean, foundAdapter As Boolean, i As Integer
Dim WMI As Object, shell As Object, exec As Object, configs As Object, config As Object


   On Error GoTo ActiveAdapter_Error

' Step 1: Get the interface IP used for default Internet route (0.0.0.0)
Set shell = CreateObject("WScript.Shell")
Set exec = shell.exec("cmd /c route print 0.0.0.0")

foundRoute = False

Do While Not exec.StdOut.AtEndOfStream
    line = Trim(exec.StdOut.ReadLine())
    If InStr(line, "0.0.0.0") = 1 Then
        parts = Split(line)
        If UBound(parts) >= 3 Then
            For i = UBound(parts) To 0 Step -1
              If InStr(parts(i), ".") Then Exit For
            Next i
            interfaceIP = parts(i)
            foundRoute = True
            Exit Do
        End If
    End If
Loop

If Not foundRoute Then
    Debug.Print "Could not find default Internet route."
    Exit Function
End If

Debug.Print "Interface used for Internet: " & interfaceIP
Debug.Print "-----------------------------------------"

' Step 2: Match that IP to a network adapter
Set WMI = GetObject("winmgmts:\\.\root\CIMV2")
Set configs = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")

foundAdapter = False

For Each config In configs
    If Not IsNull(config.IPAddress) Then
        For Each IP In config.IPAddress
            If IP = interfaceIP Then
                foundAdapter = True
                Debug.Print "Adapter with Internet access:"
                Debug.Print "  Description: " & config.Description
                Debug.Print "  MAC Address: " & config.MACAddress
                Debug.Print "  IP Address : " & IP
                If Not IsNull(config.DefaultIPGateway) Then
                    Debug.Print "  Gateway    : " & Join(config.DefaultIPGateway, ", ")
                End If
                Exit For
            End If
        Next
    End If
Next

If Not foundAdapter Then
    Debug.Print "No matching adapter found for Internet access."
End If
 

ActiveAdapter_Exit:
   Exit Function

ActiveAdapter_Error:
  Select Case Err.Number

  Case Else
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ActiveAdapter from module mdlInternet"
    Resume ActiveAdapter_Exit:
  End Select
End Function

To Include DNS Servers & IPV6 Address: -
Code:
'---------------------------------------------------------------------------------------
' Procedure : ActiveAdapter
' Author    : ChatGPT modified: bbfromgb, InView
' Date      : 23.06.2025
' Purpose   : find network adapter having internet access
'             Uses route print 0.0.0.0 to determine which interface is being used to reach the Internet.
'             Matches the IP address from the route to an adapter in WMI.
'             Displays the adapter info: Active Adapter Description, IPV4 Address, IPV6 Address, MAC Address, Gateway & DNS Servers (Pri/Sec) (Split) 
'---------------------------------------------------------------------------------------
'
Public Function ActiveAdapter() As String
    Dim shell As Object, exec As Object, line As String, parts As Variant
    Dim interfaceIP As String, ipCheck As Variant, ipListItem As Variant
    Dim WMI As Object, configs As Object, config As Object
    Dim i As Integer, found As Boolean
    Dim ipv4List As String, ipv6List As String

    On Error GoTo HandleError

    ' Step 1: Get IP used for default internet route
    Set shell = CreateObject("WScript.Shell")
    Set exec = shell.exec("cmd /c route print 0.0.0.0")

    Do While Not exec.StdOut.AtEndOfStream
        line = Trim(exec.StdOut.ReadLine)
        If InStr(line, "0.0.0.0") = 1 Then
            parts = Split(line)
            For i = UBound(parts) To 0 Step -1
                If InStr(parts(i), ".") > 0 Then
                    interfaceIP = parts(i)
                    Exit Do
                End If
            Next
        End If
    Loop

    If Len(interfaceIP) = 0 Then
        Debug.Print "Could not determine interface IP for internet access."
        Exit Function
    End If

    Debug.Print "Interface used for Internet: " & interfaceIP
    Debug.Print "-----------------------------------------"

    ' Step 2: Match IP to adapter and display info
    Set WMI = GetObject("winmgmts:\\.\root\CIMV2")
    Set configs = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")

    For Each config In configs
        If Not IsNull(config.IPAddress) Then
            For Each ipCheck In config.IPAddress
                If ipCheck = interfaceIP Then
                    found = True
                    Debug.Print "Adapter with Internet access:"
                    Debug.Print "  Description   : " & config.Description
                    Debug.Print "  MAC Address   : " & config.MACAddress

                    ipv4List = "": ipv6List = ""
                    For Each ipListItem In config.IPAddress
                        If InStr(ipListItem, ":") > 0 Then
                            ipv6List = ipv6List & ipListItem & ", "
                        Else
                            ipv4List = ipv4List & ipListItem & ", "
                        End If
                    Next
                    If Len(ipv4List) > 0 Then Debug.Print "  IPv4 Address  : " & Left(ipv4List, Len(ipv4List) - 2)
                    If Len(ipv6List) > 0 Then Debug.Print "  IPv6 Address  : " & Left(ipv6List, Len(ipv6List) - 2)

                    If Not IsNull(config.DefaultIPGateway) Then
                        Debug.Print "  Gateway       : " & Join(config.DefaultIPGateway, ", ")
                    End If

                    If Not IsNull(config.DNSServerSearchOrder) Then
                        Debug.Print "  Primary DNS   : " & config.DNSServerSearchOrder(0)
                        If UBound(config.DNSServerSearchOrder) >= 1 Then
                            Debug.Print "  Secondary DNS : " & config.DNSServerSearchOrder(1)
                        End If
                    Else
                        Debug.Print "  DNS Servers   : (none configured)"
                    End If

                    Exit For
                End If
            Next
        End If
        If found Then Exit For
    Next

    If Not found Then Debug.Print "No matching adapter found for Internet access."

CleanExit:
    Exit Function

HandleError:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in ActiveAdapter", vbCritical
    Resume CleanExit
End Function
 
To Include DNS Servers & IPV6 Address: -
Code:
'---------------------------------------------------------------------------------------
' Procedure : ActiveAdapter
' Author    : ChatGPT modified: bbfromgb, InView
' Date      : 23.06.2025
' Purpose   : find network adapter having internet access
'             Uses route print 0.0.0.0 to determine which interface is being used to reach the Internet.
'             Matches the IP address from the route to an adapter in WMI.
'             Displays the adapter info: Active Adapter Description, IPV4 Address, IPV6 Address, MAC Address, Gateway & DNS Servers (Pri/Sec) (Split)
'---------------------------------------------------------------------------------------
'
Public Function ActiveAdapter() As String
    Dim shell As Object, exec As Object, line As String, parts As Variant
    Dim interfaceIP As String, ipCheck As Variant, ipListItem As Variant
    Dim WMI As Object, configs As Object, config As Object
    Dim i As Integer, found As Boolean
    Dim ipv4List As String, ipv6List As String

    On Error GoTo HandleError

    ' Step 1: Get IP used for default internet route
    Set shell = CreateObject("WScript.Shell")
    Set exec = shell.exec("cmd /c route print 0.0.0.0")

    Do While Not exec.StdOut.AtEndOfStream
        line = Trim(exec.StdOut.ReadLine)
        If InStr(line, "0.0.0.0") = 1 Then
            parts = Split(line)
            For i = UBound(parts) To 0 Step -1
                If InStr(parts(i), ".") > 0 Then
                    interfaceIP = parts(i)
                    Exit Do
                End If
            Next
        End If
    Loop

    If Len(interfaceIP) = 0 Then
        Debug.Print "Could not determine interface IP for internet access."
        Exit Function
    End If

    Debug.Print "Interface used for Internet: " & interfaceIP
    Debug.Print "-----------------------------------------"

    ' Step 2: Match IP to adapter and display info
    Set WMI = GetObject("winmgmts:\\.\root\CIMV2")
    Set configs = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")

    For Each config In configs
        If Not IsNull(config.IPAddress) Then
            For Each ipCheck In config.IPAddress
                If ipCheck = interfaceIP Then
                    found = True
                    Debug.Print "Adapter with Internet access:"
                    Debug.Print "  Description   : " & config.Description
                    Debug.Print "  MAC Address   : " & config.MACAddress

                    ipv4List = "": ipv6List = ""
                    For Each ipListItem In config.IPAddress
                        If InStr(ipListItem, ":") > 0 Then
                            ipv6List = ipv6List & ipListItem & ", "
                        Else
                            ipv4List = ipv4List & ipListItem & ", "
                        End If
                    Next
                    If Len(ipv4List) > 0 Then Debug.Print "  IPv4 Address  : " & Left(ipv4List, Len(ipv4List) - 2)
                    If Len(ipv6List) > 0 Then Debug.Print "  IPv6 Address  : " & Left(ipv6List, Len(ipv6List) - 2)

                    If Not IsNull(config.DefaultIPGateway) Then
                        Debug.Print "  Gateway       : " & Join(config.DefaultIPGateway, ", ")
                    End If

                    If Not IsNull(config.DNSServerSearchOrder) Then
                        Debug.Print "  Primary DNS   : " & config.DNSServerSearchOrder(0)
                        If UBound(config.DNSServerSearchOrder) >= 1 Then
                            Debug.Print "  Secondary DNS : " & config.DNSServerSearchOrder(1)
                        End If
                    Else
                        Debug.Print "  DNS Servers   : (none configured)"
                    End If

                    Exit For
                End If
            Next
        End If
        If found Then Exit For
    Next

    If Not found Then Debug.Print "No matching adapter found for Internet access."

CleanExit:
    Exit Function

HandleError:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in ActiveAdapter", vbCritical
    Resume CleanExit
End Function

As Above (No CMD Window Flash)

Code:
'---------------------------------------------------------------------------------------
' Procedure : ActiveAdapter
' Author    : ChatGPT modified: bbfromgb, InView
' Date      : 23.06.2025
' Purpose   : find network adapter having internet access (No CMD Window Flash)
'             Uses route print 0.0.0.0 to determine which interface is being used to reach the Internet.
'             Matches the IP address from the route to an adapter in WMI.
'             Displays the adapter info: Active Adapter Description, IPV4 Address, IPV6 Address, MAC Address, Gateway & DNS Servers (Pri/Sec) (Split)
'---------------------------------------------------------------------------------------
'
Public Function ActiveAdapter() As String
    Dim shell As Object, fso As Object, tempFile As String
    Dim line As String, parts As Variant, interfaceIP As String
    Dim WMI As Object, configs As Object, config As Object
    Dim ipCheck As Variant, ipListItem As Variant
    Dim i As Integer, found As Boolean
    Dim ipv4List As String, ipv6List As String

    On Error GoTo HandleError

    ' Step 1: Run route command silently and capture output
    Set shell = CreateObject("WScript.Shell")
    Set fso = CreateObject("Scripting.FileSystemObject")
    tempFile = Environ("TEMP") & "\route_output.txt"
    shell.Run "cmd /c route print 0.0.0.0 > """ & tempFile & """", 0, True

    ' Step 2: Read the output file to find the interface IP
    If Not fso.FileExists(tempFile) Then
        Debug.Print "Route output file not found."
        Exit Function
    End If

    With fso.OpenTextFile(tempFile, 1)
        Do While Not .AtEndOfStream
            line = Trim(.ReadLine)
            If InStr(line, "0.0.0.0") = 1 Then
                parts = Split(line)
                For i = UBound(parts) To 0 Step -1
                    If InStr(parts(i), ".") > 0 Then
                        interfaceIP = parts(i)
                        Exit Do
                    End If
                Next
            End If
        Loop
        .Close
    End With
    fso.DeleteFile tempFile

    If Len(interfaceIP) = 0 Then
        Debug.Print "Could not determine interface IP for internet access."
        Exit Function
    End If

    Debug.Print "Interface used for Internet: " & interfaceIP
    Debug.Print "-----------------------------------------"

    ' Step 3: Match IP to adapter and display info
    Set WMI = GetObject("winmgmts:\\.\root\CIMV2")
    Set configs = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")

    For Each config In configs
        If Not IsNull(config.IPAddress) Then
            For Each ipCheck In config.IPAddress
                If ipCheck = interfaceIP Then
                    found = True
                    Debug.Print "Adapter with Internet access:"
                    Debug.Print "  Description   : " & config.Description
                    Debug.Print "  MAC Address   : " & config.MACAddress

                    ipv4List = "": ipv6List = ""
                    For Each ipListItem In config.IPAddress
                        If InStr(ipListItem, ":") > 0 Then
                            ipv6List = ipv6List & ipListItem & ", "
                        Else
                            ipv4List = ipv4List & ipListItem & ", "
                        End If
                    Next
                    If Len(ipv4List) > 0 Then Debug.Print "  IPv4 Address  : " & Left(ipv4List, Len(ipv4List) - 2)
                    If Len(ipv6List) > 0 Then Debug.Print "  IPv6 Address  : " & Left(ipv6List, Len(ipv6List) - 2)

                    If Not IsNull(config.DefaultIPGateway) Then
                        Debug.Print "  Gateway       : " & Join(config.DefaultIPGateway, ", ")
                    End If

                    If Not IsNull(config.DNSServerSearchOrder) Then
                        Debug.Print "  Primary DNS   : " & config.DNSServerSearchOrder(0)
                        If UBound(config.DNSServerSearchOrder) >= 1 Then
                            Debug.Print "  Secondary DNS : " & config.DNSServerSearchOrder(1)
                        End If
                    Else
                        Debug.Print "  DNS Servers   : (none configured)"
                    End If

                    Exit For
                End If
            Next
        End If
        If found Then Exit For
    Next

    If Not found Then Debug.Print "No matching adapter found for Internet access."

CleanExit:
    Exit Function

HandleError:
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in ActiveAdapter", vbCritical
    Resume CleanExit
End Function
 
Optional Output: -


Code:
'---------------------------------------------------------------------------------------
' Procedure : GetActiveAdapterDetailsOptionalOutput
' Author    : ChatGPT modified: bbfromgb, InView
' Date      : 23.06.2025
' Purpose   : Find network adapter having internet access (No CMD Window Flash)
'             Outputs Adapter Description, IPV4, IPV6, MAC, Gateway, and DNS Details (Split)
'
' Usage     : Call GetActiveAdapterDetails(True, True,True) ' Choice Output to Immediate, MsgBox, and HTML (AutoOpen)
'-----------------------------------------------------------------------------------------

Public Function GetActiveAdapterDetails(Optional PrintToDebug As Boolean = True, Optional ShowMsgBox As Boolean = False, Optional ExportAsHTML As Boolean = False) As String
    ' Declares required object and variables
    Dim shell As Object, fso As Object, tempFile As String
    Dim WMI As Object, configs As Object, config As Object
    Dim line As String, parts As Variant, interfaceIP As String
    Dim ipCheck As Variant, ipListItem As Variant
    Dim i As Integer, found As Boolean
    Dim ipv4List As String, ipv6List As String, output As String
    Dim htmlOutput As String, htmlPath As String, htmlFile As Object

    On Error GoTo HandleError

    ' Create scripting and shell objects
    Set shell = CreateObject("WScript.Shell")
    Set fso = CreateObject("Scripting.FileSystemObject")

    ' Define temp output file path
    tempFile = Environ("TEMP") & "\route_output.txt"

    ' Run route command silently to get routing table and redirect output to temp file
    shell.Run "cmd /c route print 0.0.0.0 > """ & tempFile & """", 0, True

    ' Exit if the route output file doesn't exist (safety check)
    If Not fso.FileExists(tempFile) Then Exit Function

    ' Read route output file to extract interface IP for default route (0.0.0.0)
    With fso.OpenTextFile(tempFile, 1)
        Do While Not .AtEndOfStream
            line = Trim(.ReadLine)
            If InStr(line, "0.0.0.0") = 1 Then
                parts = Split(line)
                ' Scan backwards to find something that looks like an IP address
                For i = UBound(parts) To 0 Step -1
                    If InStr(parts(i), ".") > 0 Then
                        interfaceIP = parts(i)
                        Exit Do
                    End If
                Next
            End If
        Loop
        .Close
    End With

    ' Delete temp file after reading
    fso.DeleteFile tempFile

    ' If no IP address was found, terminate early
    If Len(interfaceIP) = 0 Then Exit Function

    ' Use WMI to get all active (IP-enabled) network adapters
    Set WMI = GetObject("winmgmts:\\.\root\CIMV2")
    Set configs = WMI.ExecQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = TRUE")

    ' Loop through each adapter
    For Each config In configs
        If Not IsNull(config.IPAddress) Then
            ' Check if this adapter owns the interface IP from the route
            For Each ipCheck In config.IPAddress
                If ipCheck = interfaceIP Then
                    found = True
                    ipv4List = "": ipv6List = ""

                    ' Split adapter's IPs into separate IPv4 and IPv6 lists
                    For Each ipListItem In config.IPAddress
                        If InStr(ipListItem, ":") > 0 Then
                            ipv6List = ipv6List & ipListItem & ", "
                        Else
                            ipv4List = ipv4List & ipListItem & ", "
                        End If
                    Next

                    ' Format output as plain text
                    output = "Active Network Adapter Info:" & vbCrLf & vbCrLf
                    output = output & "  Description   : " & config.Description & vbCrLf
                    output = output & "  MAC Address   : " & config.MACAddress & vbCrLf
                    If Len(ipv4List) > 0 Then output = output & "  IPv4 Address  : " & Left(ipv4List, Len(ipv4List) - 2) & vbCrLf
                    If Len(ipv6List) > 0 Then output = output & "  IPv6 Address  : " & Left(ipv6List, Len(ipv6List) - 2) & vbCrLf
                    If Not IsNull(config.DefaultIPGateway) Then output = output & "  Gateway       : " & Join(config.DefaultIPGateway, ", ") & vbCrLf

                    ' Append DNS server information
                    If Not IsNull(config.DNSServerSearchOrder) Then
                        output = output & "  Primary DNS   : " & config.DNSServerSearchOrder(0) & vbCrLf
                        If UBound(config.DNSServerSearchOrder) >= 1 Then
                            output = output & "  Secondary DNS : " & config.DNSServerSearchOrder(1) & vbCrLf
                        End If
                    Else
                        output = output & "  DNS Servers   : (none configured)" & vbCrLf
                    End If

                    ' Generate HTML version of same output, replacing line breaks
                    htmlOutput = "<html><head><style>" & _
                        "body{font-family:Segoe UI;line-height:1.4;} h2{color:#2E8B57;} " & _
                        "pre{background:#f0f0f0;padding:10px;}</style></head><body>"
                    htmlOutput = htmlOutput & "<h2>Active Network Adapter Info</h2><pre>" & Replace(output, vbCrLf, vbLf) & "</pre></body></html>"
                    htmlPath = Environ("TEMP") & "\ActiveNetworkAdapter.html"

                    ' If ExportAsHTML is enabled, write to .html file and open in browser
                    If ExportAsHTML Then
                        Set htmlFile = fso.CreateTextFile(htmlPath, True)
                        htmlFile.Write htmlOutput
                        htmlFile.Close
                        shell.Run """" & htmlPath & """", 1, False
                    End If

                    Exit For ' Exit IP loop
                End If
            Next
        End If
        If found Then Exit For ' Exit adapter loop once a match is found
    Next

    ' Optional output methods
    If PrintToDebug And Len(output) > 0 Then Debug.Print output
    If ShowMsgBox And Len(output) > 0 Then MsgBox output, vbInformation, "Active Network Adapter"

    GetActiveAdapterDetails = output
    Exit Function

HandleError:
    ' Display error message if anything fails during execution
    MsgBox "Error " & Err.Number & " (" & Err.Description & ") in GetActiveAdapterDetails", vbCritical
End Function
 

Users who are viewing this thread

Back
Top Bottom