Monday, May 19, 2025

Retrieve Local IP Addresses

I received a question today if I knew how to retrieve the local machine's IP address, so they can use it for an audit trail log. I didn't have a ready-made solution, so I had to search for one. Luckily, I found VBA - Determine Your PC's IP Address created by Daniel Pineault at DevHut. I was very happy to pass this info along to the person who asked me the question as I am sure it would really help them in their project.

Later on, I began to wonder, just for fun, how I might modify Daniel's code to use regular expressions. I am not saying using regular expressions would make it better. I was just curious to see how differently it would look like. The below function is what I came up with after a quick search for a good regex pattern.

I am not trying to create a replacement function, so I merely concentrated on grabbing the IPv4 addresses and did not include any error checks in the code. If you decide to use this, please test it thoroughly and let me know how it can be improved. Thank you!

Public Function GetMyIPs() As String
'thedbguy@gmail.com
'5/19/2025
'https://www.devhut.net/vba-determine-your-pcs-ip-address/
'https://ihateregex.io/expr/ip/

Dim regEx As Object
Dim regExMatch As Object
Dim var As Variant
Dim strIPInfo As String
Dim strResult As String

'use ipconfig to get IP info
CreateObject("Wscript.Shell").Run "cmd /c ipconfig | findstr /R /C:""IPv4 Address"" | clip", 0, True
With CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}") 'use clipboard
    .GetFromClipboard
    strIPInfo = .GetText
End With

'parse IP info
Set regEx = CreateObject("VBScript.RegExp")
With regEx
    .Global = True
    .IgnoreCase = True
    .Pattern = "(\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}"
    Set regExMatch = .Execute(strIPInfo)
    For Each var In regExMatch
        strResult = strResult & ";" & var
    Next
    
End With

If strResult <> "" Then
    GetMyIPs = Mid(strResult, 2)
End If

Set regExMatch = Nothing
Set regEx = Nothing

End Function