Search code examples
vbaexcelmsinet

How to retrieve this computer's IP address?


What is the least cumbersome (module-inclusion, code lenght, etc) way to retrieve the machine IP address (of the first interface open)? I know of some solutions using MSINET, but I believe we can do better. Don't reply

Function HomeIP() as Atring
HomeIP= "127.0.0.1"
End Function

because it's not that funny... or correct. The scenario is a question wiht a document ID feature I'm trying to build a reply for.


Solution

  • Here's an adapted example from Technet:

    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
    

    It requires that you have Microsoft WMI Scripting Library in the project's references.