Access VBA to get IP4 address

I have a function that gets IP4 and IP6 addresses, does anyone know how to just get IP4 address? (e.g. 192.9.1.1)
Function GetIPAddress()
    Const strComputer As String = "."   ' Computer name. Dot means local computer
    Dim objWMIService, IPConfigSet, IPConfig, IPAddress, i
    Dim strIPAddress As String

    ' Connect to the WMI service
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    ' Get all TCP/IP-enabled network adapters
    Set IPConfigSet = objWMIService.ExecQuery _
        ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE")

    ' Get all IP addresses associated with these adapters
    For Each IPConfig In IPConfigSet
        IPAddress = IPConfig.IPAddress
        If Not IsNull(IPAddress) Then
            strIPAddress = strIPAddress & Join(IPAddress, ", ")
        End If
    Next

    GetIPAddress = strIPAddress
End Function

Open in new window

HKFueyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Gustav BrockCIOCommented:
Like this modification?:

        If Not IsNull(IPAddress) Then
'            strIPAddress = strIPAddress & Join(IPAddress, ", ")
            strIPAddress = strIPAddress & IPAddress(0)
        End If

/gustav
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jim Dettman (Microsoft MVP/ EE MVE)President / OwnerCommented:
The problem your referring to I'm assuming is that the code you have returns the IP address of every interface in the system.

 Below is the code I have for picking up the "Main" (LANA 0) address for a machine.   I have not used this extensivley and don't know that it will always return "the IP" of the machine.

Jim.

Sub main()
    Dim error As Long
    Dim FixedInfoSize As Long
    Dim AdapterInfoSize As Long
    Dim i As Integer
    Dim PhysicalAddress  As String
    Dim NewTime As Date
    Dim AdapterInfo As IP_ADAPTER_INFO
    Dim AddrStr As IP_ADDR_STRING
    Dim FixedInfo As FIXED_INFO
    Dim Buffer As IP_ADDR_STRING
    Dim pAddrStr As Long
    Dim pAdapt As Long
    Dim Buffer2 As IP_ADAPTER_INFO
    Dim FixedInfoBuffer() As Byte
    Dim AdapterInfoBuffer() As Byte

    ' Get the main IP configuration information for this machine
    ' using a FIXED_INFO structure.
    FixedInfoSize = 0
    error = GetNetworkParams(ByVal 0&, FixedInfoSize)
    If error <> 0 Then
        If error <> ERROR_BUFFER_OVERFLOW Then
           MsgBox "GetNetworkParams sizing failed with error " & error
           Exit Sub
        End If
    End If
    ReDim FixedInfoBuffer(FixedInfoSize - 1)

    error = GetNetworkParams(FixedInfoBuffer(0), FixedInfoSize)
    If error = 0 Then
            CopyMemory FixedInfo, FixedInfoBuffer(0), FixedInfoSize
            MsgBox "Host Name:  " & FixedInfo.HostName
            MsgBox "DNS Servers:  " & FixedInfo.DnsServerList.IpAddress
            pAddrStr = FixedInfo.DnsServerList.Next
            Do While pAddrStr <> 0
                  CopyMemory Buffer, ByVal pAddrStr, LenB(Buffer)
                  MsgBox "DNS Servers:  " & Buffer.IpAddress
                  pAddrStr = Buffer.Next
            Loop

            Select Case FixedInfo.NodeType
                       Case 1
                                  MsgBox "Node type: Broadcast"
                       Case 2
                                  MsgBox "Node type: Peer to peer"
                       Case 4
                                  MsgBox "Node type: Mixed"
                       Case 8
                                  MsgBox "Node type: Hybrid"
                       Case Else
                                  MsgBox "Unknown node type"
            End Select

            MsgBox "NetBIOS Scope ID:  " & FixedInfo.ScopeId
            If FixedInfo.EnableRouting Then
                       MsgBox "IP Routing Enabled "
            Else
                       MsgBox "IP Routing not enabled"
            End If
            If FixedInfo.EnableProxy Then
                       MsgBox "WINS Proxy Enabled "
            Else
                       MsgBox "WINS Proxy not Enabled "
            End If
            If FixedInfo.EnableDns Then
                      MsgBox "NetBIOS Resolution Uses DNS "
            Else
                      MsgBox "NetBIOS Resolution Does not use DNS  "
            End If
    Else
            MsgBox "GetNetworkParams failed with error " & error
            Exit Sub
    End If

    ' Enumerate all of the adapter specific information using the
    ' IP_ADAPTER_INFO structure.
    ' Note:  IP_ADAPTER_INFO contains a linked list of adapter entries.

    AdapterInfoSize = 0
    error = GetAdaptersInfo(ByVal 0&, AdapterInfoSize)
    If error <> 0 Then
        If error <> ERROR_BUFFER_OVERFLOW Then
           MsgBox "GetAdaptersInfo sizing failed with error " & error
           Exit Sub
        End If
    End If
    ReDim AdapterInfoBuffer(AdapterInfoSize - 1)

    ' Get actual adapter information
    error = GetAdaptersInfo(AdapterInfoBuffer(0), AdapterInfoSize)
    If error <> 0 Then
       MsgBox "GetAdaptersInfo failed with error " & error
       Exit Sub
    End If

    ' Allocate memory
     CopyMemory AdapterInfo, AdapterInfoBuffer(0), AdapterInfoSize
    pAdapt = AdapterInfo.Next

    Do
     CopyMemory Buffer2, AdapterInfo, AdapterInfoSize
       Select Case Buffer2.Type
              Case MIB_IF_TYPE_ETHERNET
                   MsgBox "Adapter name: Ethernet adapter "
              Case MIB_IF_TYPE_TOKENRING
                   MsgBox "Adapter name: Token Ring adapter "
              Case MIB_IF_TYPE_FDDI
                   MsgBox "Adapter name: FDDI adapter "
              Case MIB_IF_TYPE_PPP
                   MsgBox "Adapter name: PPP adapter"
              Case MIB_IF_TYPE_LOOPBACK
                   MsgBox "Adapter name: Loopback adapter "
              Case MIB_IF_TYPE_SLIP
                   MsgBox "Adapter name: Slip adapter "
              Case Else
                   MsgBox "Adapter name: Other adapter "
       End Select
       MsgBox "AdapterDescription: " & Buffer2.Description

       PhysicalAddress = ""
       For i = 0 To Buffer2.AddressLength - 1
           PhysicalAddress = PhysicalAddress & Hex(Buffer2.Address(i))
       Next
       MsgBox "Physical Address: " & PhysicalAddress

       If Buffer2.DhcpEnabled Then
          MsgBox "DHCP Enabled "
       Else
          MsgBox "DHCP disabled"
       End If

       MsgBox "IP Address: " & Buffer2.IpAddressList.IpAddress
       MsgBox "Subnet Mask: " & Buffer2.IpAddressList.IpMask
       pAddrStr = Buffer2.IpAddressList.Next
       Do While pAddrStr <> 0
          CopyMemory Buffer, Buffer2.IpAddressList, LenB(Buffer)
          MsgBox "IP Address: " & Buffer.IpAddress
          MsgBox "Subnet Mask: " & Buffer.IpMask
          pAddrStr = Buffer.Next
          If pAddrStr <> 0 Then
             CopyMemory Buffer2.IpAddressList, ByVal pAddrStr, _
                        LenB(Buffer2.IpAddressList)
          End If
       Loop

       MsgBox "Default Gateway: " & Buffer2.GatewayList.IpAddress
       pAddrStr = Buffer2.GatewayList.Next
       Do While pAddrStr <> 0
          CopyMemory Buffer, Buffer2.GatewayList, LenB(Buffer)
          MsgBox "IP Address: " & Buffer.IpAddress
          pAddrStr = Buffer.Next
          If pAddrStr <> 0 Then
             CopyMemory Buffer2.GatewayList, ByVal pAddrStr, _
                        LenB(Buffer2.GatewayList)
          End If
       Loop

       MsgBox "DHCP Server: " & Buffer2.DhcpServer.IpAddress
       MsgBox "Primary WINS Server: " & _
              Buffer2.PrimaryWinsServer.IpAddress
       MsgBox "Secondary WINS Server: " & _
              Buffer2.SecondaryWinsServer.IpAddress

       ' Display time.
       NewTime = DateAdd("s", Buffer2.LeaseObtained, #1/1/1970#)
       MsgBox "Lease Obtained: " & _
              CStr(Format(NewTime, "dddd, mmm d hh:mm:ss yyyy"))

       NewTime = DateAdd("s", Buffer2.LeaseExpires, #1/1/1970#)
       MsgBox "Lease Expires :  " & _
              CStr(Format(NewTime, "dddd, mmm d hh:mm:ss yyyy"))
       pAdapt = Buffer2.Next
       If pAdapt <> 0 Then
           CopyMemory AdapterInfo, ByVal pAdapt, AdapterInfoSize
        End If
      Loop Until pAdapt = 0
End Sub

Open in new window

0
Gustav BrockCIOCommented:
The original function could be modified to return either the IPv4 or -6 address and, if more than one address is found, to concatenate these:
Public Function GetIPAddress(Optional ByVal IPv6 As Boolean) As String

    Const cstrComputer  As String = "." ' Computer name. Dot means local computer.
    Const cstrSeparator As String = ";" ' Separator if more than one address is found.
    
    Dim objWMIService   As Object
    Dim IPConfigSet     As Variant
    Dim IPConfig        As Variant
    Dim IPAddress       As Variant
    Dim strIPAddress    As String

    ' Connect to the WMI service.
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & cstrComputer & "\root\cimv2")

    ' Get all TCP/IP-enabled network adapters.
    Set IPConfigSet = objWMIService.ExecQuery _
        ("Select * From Win32_NetworkAdapterConfiguration Where IPEnabled = TRUE")

    ' Get all IP addresses associated with these adapters.
    For Each IPConfig In IPConfigSet
        IPAddress = IPConfig.IPAddress
        If Not IsNull(IPAddress) Then
            strIPAddress = _
                IIf(Len(strIPAddress) = 0, "", strIPAddress & cstrSeparator) & IPAddress(Abs(IPv6))
        End If
    Next
    
    GetIPAddress = strIPAddress
    
End Function

Open in new window

/gustav
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

HKFueyAuthor Commented:
Fist post works perfectly, the other post are really useful too. Thanks very much
0
Gustav BrockCIOCommented:
You are welcome!

/gustav
0
aikimarkCommented:
Whenever possible, I try to let the query filter the data as much as possible.  In this case, I'll check for a not null condition.

Next, I use the regexp object to parse the IPAddress.
Function GetIPAddress()
    Const strComputer As String = "."   ' Computer name. Dot means local computer
    Dim objWMIService, IPConfigSet, IPConfig, IPAddress, i
    Dim strIPAddress As String
    Dim oRE As Object
    Dim oMatches As Object

    Set oRE = CreateObject("vbscript.regexp")
    oRE.Pattern = "(\d+.\d+.\d+.\d+)"

    ' Connect to the WMI service
    Set objWMIService = GetObject("winmgmts:" _
        & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

    ' Get all TCP/IP-enabled network adapters
    Set IPConfigSet = objWMIService.ExecQuery _
        ("Select * from Win32_NetworkAdapterConfiguration Where IPEnabled=TRUE and IPAddress Is Not Null")

    ' Get all IP addresses associated with these adapters
    For Each IPConfig In IPConfigSet
        IPAddress = IPConfig.IPAddress
        If oRE.test(IPAddress) Then
            Set oMatches = oRE.Execute(IPAddress)
            strIPAddress = strIPAddress & ", " & oMatches(0)
        end if
    Next

    GetIPAddress = Mid(strIPAddress,3)
End Function

Open in new window

0
Gustav BrockCIOCommented:
IPAddress is not a field in the query, so your code doesn't run (here).

/gustav
0
aikimarkCommented:
I see.  IPAddress is a string array field type.  Since it is not an atomic data type, the normal rules for querying (WQL) do not apply.  Thanks, Gustav.

In addition to the above parsing methods, does anyone know if the (0) item in the IPAddress array will always point to the IPV4 address or if it might be elsewhere in the array.  If it will always be in the zero position, then we can add
IPConfig.IPAddress(0)

Open in new window

as a parsing method.
0
Gustav BrockCIOCommented:
I wouldn't expect that position to be random.

/gustav
0
aikimarkCommented:
I wouldn't expect that position to be random.
If there is only an IPV6 address, should we see an empty zero position string?
0
Gustav BrockCIOCommented:
Good question. You better check that out.

/gustav
0
aikimarkCommented:
You better check that out.
Unfortunately, I only have IPV4 in my environment and no way to mock up an IPV6-only environment to test.
0
Gustav BrockCIOCommented:
Same here.

/gustav
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Access

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.