Windows Batch - How to get the external IP into a batch-file variable

前端 未结 3 1661
臣服心动
臣服心动 2020-12-17 01:23

I am making a program that checks if a user\'s IP is a certain IP address.

Currently, I created a successful internal IP version:

@echo off
set userI         


        
相关标签:
3条回答
  • 2020-12-17 01:39

    With pure batch/already present tools:
    EDIT: changed the batch to properly handle also IPv6 addresses

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

    Reference

    Another one with powershell:

    @Echo off
    For /f %%A in (
      'powershell -command "(Invoke-Webrequest "http://api.ipify.org").content"'
    ) Do Set ExtIP=%%A
    Echo External IP is : %ExtIP%
    

    And another slightly different powershell variant:

    @Echo off
    For /f %%A in (
      'powershell -nop -c "(Invoke-RestMethod http://ipinfo.io/json).IP"'
    ) Do Set ExtIP=%%A
    Echo External IP is : %ExtIP%
    
    0 讨论(0)
  • 2020-12-17 01:43

    To get your public IP without additional parsing do this:

    curl "http://api.ipify.org"

    EDIT:

    This version is more reliable across windows language versions:

    for /f "tokens=3 delims== " %%A in ('
    nslookup -debug myip.opendns.com. resolver1.opendns.com 2^>NUL^|findstr /C:"internet address"
    ') do set "ext_ip=%%A"
    
    0 讨论(0)
  • 2020-12-17 01:55

    First it seems there is a . too much after the first .com.

    Second when using your command with simply google.com and echo %a I get the following:

    " xx.xx.xx.x" without the quotes and with two leading spaces!

    So your if will never be true!

    Change it to something like this: if "%%a"==" xx.xx.xx.x" Goto:good and you should be fine.

    0 讨论(0)
提交回复
热议问题