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

amorosik

Member
Local time
Today, 16:42
Joined
Apr 18, 2020
Messages
551
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
 

Users who are viewing this thread

Back
Top Bottom