Published on by

If your computer sits on a network behind NAT it is difficult to discover your public IP address programatically without querying some web service. The problem with web services is that they are slow and unreliable, they may go through proxy and thus be unable to provide the right information, or the access to them may be blocked by firewall.

The approach which works most of the time is to use DNS query to find your own public IP address. This is possible thanks to special placeholder A record which, when you query their DNS server, resolves to your own public IP.

You can do this programatically in any language, but can you do it in a Windows batch file? Why yes, yes you can!

FOR /F "usebackq tokens=2 delims=: " %%A IN (`nslookup 2^>^&1 ^| FINDSTR /C:"Address"`) DO SET MYIP=%%A

The above batch file will query the DNS server and place the result on the clipboard. Please note that the dot right after is intentional to avoid appending domain search suffixes, the carets are there to escape special characters, and ECHO | SET /P=... is used to strip the end-of-line characters from the result to get only the IP address.