Setup a port forwarding by batch file

eye-catch Other techs

I needed to set up a port forwarding to access a machine via another machine. The setting was reset whenever the machine restarts, so I created a script.

Sponsored links

Port forwarding setting

This is the network structure. I needed to access Machine2 but it’s impossible to communicate with Machine2 from Actor without port forwarding because the packet ends on Machine.

Diagram for the network

Add a new setting

This is a template script to create a new port forwarding setting.

sc config "iphlpsvc" start=demand
sc start iphlpsvc
netsh interface portproxy add v4tov4 listenaddress=<src_address> listenport=<src_port> connectaddress=<dest_address> connectport=<dest_port>
netstat -ano | findstr :<port_number>
pause

The placeholder must be replaced with an actual value. The names of placeholder correspond to the image above.

What this batch file does is as follows.

  1. Change the startup type of IP helper service to Manual
  2. Start the IP helper service
  3. Setup the port forwarding
  4. Show the setting

Delete a setting

If it’s necessary to delete the setting, use this script.

netsh interface portproxy delete v4tov4 listenaddress=<src_address> listenport=<src_port>
Sponsored links

Firewall rule

The port number specified above might not be open. A new firewall rule needs to be added in this case.

Add the port setting

This direction is for a response, namely, Destination (Machine2) to Actor.

netsh advfirewall firewall add rule name="firewall-rule-name" protocol=TCP dir=in localip=<dest_address> localport=<dest_port> action=allow

I assume the network between Machine and Machine2 is a private network. Therefore, localip and localport is used in the script.

Delete the port setting

netsh advfirewall firewall delete rule name="firewall-rule-name"
# Test-NetConnection -ComputerName <Machine Name> -Port <number>
Test-NetConnection -ComputerName MACHINE_NAME -Port 12345

Reference: http://woshub.com/port-forwarding-in-windows/

Comments

Copied title and URL