HOWTO: Find public IP and place it on the clipboard using CMD
Published on 2016/12/28 by Igor Levicki
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 opendns.com special placeholder A record myip.opendns.com 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!
@ECHO OFF FOR /F "usebackq tokens=2 delims=: " %%A IN (`nslookup myip.opendns.com. resolver1.opendns.com 2^>^&1 ^| FINDSTR /C:"Address"`) DO SET MYIP=%%A ECHO | SET /P="%MYIP%" | CLIP
The above batch file will query the DNS server and place the result on the clipboard. Please note that the dot right after myip.opendns.com 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.