I am trying to create a batch file that port forwards my IP. The IP can be found with the command ipconfig | findstr IPv4
, but there are multiple internet adapters and multiple IP addresses. I want to get only one address like 192.168.40.??
192.168.56.1 and 192.168.56.2 is my VirtualBox adapter. I'm not sure how to set the condition in the if statement.
This is the Windows batch file (*.bat):
D:\>ipconfig | findstr IPv4
IPv4 adress . . . . . . . . . : 192.168.56.2
IPv4 adress . . . . . . . . . : 192.168.56.1
IPv4 adress . . . . . . . . . : 192.168.40.19
I tried the following batch file:
@echo off
setlocal
setlocal enabledelayedexpansion
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr IPv4`) do (
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
for /f "tokens=1-4 delims=." %%c in ("%%b") do (
set _o1=%%c
set _o2=%%d
set _o3=%%e
set _o4=%%f
set _4octet=!_o1:~1!.!_o2!.!_o3!.!_o4!
echo ==start port fowarding==
netsh interface portproxy add v4tov4 listenport=8080 listenaddress=!_4octet! connectport=8080 connectaddress=192.168.56.1
echo ========================
netsh interface portproxy show v4tov4
)
)
)
endlocal
But this runs on all of my adapters:
address port address port
--------------- ---------- --------------- ----------
192.168.56.2 8080 192.168.56.1 8080 <- not want
192.168.56.1 8080 192.168.56.1 8080 <- not want
192.168.40.19 8080 192.168.56.1 8080 <- i want only
I then tried:
@echo off
setlocal
setlocal enabledelayedexpansion
for /f "usebackq tokens=*" %%a in (`ipconfig ^| findstr IPv4`) do (
for /f delims^=^:^ tokens^=2 %%b in ('echo %%a') do (
for /f "tokens=1-4 delims=." %%c in ("%%b") do (
set _o1=%%c
set _o2=%%d
set _o3=%%e
set _o4=%%f
set _4octet=!_o1:~1!.!_o2!.!_o3!.!_o4!
echo ==start port fowarding==
if !_4octet!==192.168.56.1
(
)
else if !_4octet!==192.168.56.2
(
)
else
netsh interface portproxy add v4tov4 listenport=8080 listenaddress=!_4octet! connectport=8080 connectaddress=192.168.56.1
echo ========================
netsh interface portproxy show v4tov4
)
)
)
endlocal
But I receive the error:
The syntax of the command is incorrect.
Perhaps the cause is that the variable (!_4octet!) Is not working properly.
if !_4octet! == 192.168.56.1 (
Can you help me with this problem?
If you want to get something like this ip 192.168.40.*
You can use a little regex with the command findstr
like this :
ipconfig | findstr IPv4 | findstr /r /c:"192.168.40.*"
You can see more help here findstr /?
/R /C:string Use string as a regular expression.
So, with a batch script you can do it to set your IP into Variable like this :
@echo off
SetLocal EnableDelayedExpansion
for /f "usebackq delims=: tokens=2" %%a in (`ipconfig ^| findstr IPv4 ^| findstr /r /c:"192.168.40.*"`) do (
Set "MyIP=%%a"
Set "MyIP=!MyIP!"
set "MyIP=!MyIP: =!"
)
echo MyIP="!MyIP!"
pause