I am trying to get the external IP address of a network to see if it is on the same network as other PCs, but my script isn't working. My main problem is that: No matter what I do I can't seem to get the line with the external ip address from nslookup myip.opendns.com resolver1.opendns.com Here is what I have:

nslookup myip.opendns.com resolver1.opendns.com>IP
set nu1m=0
Setlocal EnableDelayedExpansion
for /F "tokens=*" %%A in  (IP) do (set /a nu1m+=1 & if !num!==6 set ip=%%A)
echo %ip% >Out.txt

I've tried replacing %ip% with !ip! but no matter what I do the ip variable is empty. Any idea what I'm doing wrong?

  • Try omitting and not using any of the conditional IF and SET /A logic and simply try for /f "tokens=*" %%A in (IP) do set ip=%%A and then check %ip% and see if it's the expected result. Since you are using the set command, it will set the last token from the nslookup command which should be the last IP from its output which is what I think you need so give that a try as it may be as simple as that rather than trying to count up and then only set the last output which would be 6 if I understand the logic correctly but it shouldn't be needed actually. – Pimp Juice IT May 24 '18 at 13:57
  • To remove the extra colon / spaces try this version. – LotPings May 24 '18 at 16:21
  • @PimpJuiceIT I'm a fool that is perfect thank you! – Mark Deven May 24 '18 at 20:26
  • And thanks @LotPings, would you mind rephrasing that as an answer so I can accept it? – Mark Deven May 24 '18 at 20:26
  • Glad to help regardless for simple things like that when I can. Sometimes overlooking simple things is very easy to do—I've done it many times myself over complicating solutions because I forgot to try the simple stuff first... Cheers!! – Pimp Juice IT May 25 '18 at 0:22

Instead of writing nslookup output to a file you can parse it directly with a for /f as shown in this version I repeat here for easier lookup:

@Echo off
for /f "tokens=2 delims=: " %%A in (
  'nslookup myip.opendns.com. resolver1.opendns.com 2^>NUL^|find "Address:"'
) Do set ExtIP=%%A
Echo External IP is : %ExtIP%
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.