how to forward a port from a wsl2 vm to your local network

step 1: create firewall rule

to open the firewall manager i usually just search firewall. if that doesnt work try pressing win + r and entering wf.msc.

click on "inbound rules" on the left panel, then click "new rule" on the right panel.

screenshot of "Windows Defender Firewall with Advanced Security", highlighting the buttons you need to press

create a port rule, specify which port you want to open up, and the rest of the defaults are fine as-is. you can name the rule anything

screenshot of "New Inbound Rule Wizard". i selected the "Port" rule type same wizard. in the textbox next to "Specific local ports" i typed "1234" as an example

step 2: expose the port to outside localhost

the other version of this step where i thought you could just connect to localhost (i swear it worked when i first tried it but now it doesnt)

open an admin powershell console

(i used to do this by searching for powershell, and clicking run as administrator, but now i just have a Windows Terminal profile for it)

screenshot of window's search bar. i searched powershell and my mouse is over the Run as Administrator button on the right panel

run netsh interface portproxy add v4tov4 listenport=YOUR_PORT connectport=YOUR_PORT connectaddress=127.0.0.1

inside wsl, run ip -br a (you may need to install iproute2 first)

copy the ip address thats in the eth0 line.

screenshot of Windows Terminal. i ran "wsl ip -br a", and it outputted 2 lines. the last line begins with eth0, and has an ipv4 address in the middle.

open an admin powershell console

(i used to do this by searching for powershell, and clicking run as administrator, but now i just have a Windows Terminal profile for it)

screenshot of window's search bar. i searched powershell and my mouse is over the Run as Administrator button on the right panel

run netsh interface portproxy add v4tov4 listenport=YOUR_PORT connectport=YOUR_PORT connectaddress=THE_IP_ADDRESS

and youre done! unless you want to port forward to the internet, instead of just your local network. in that case just google a random tutorial for that step idk

this probably wont work with ipv6. i suspect you could just replace v4tov4 with v6tov6 and the ipv4 ip with the other ipv6 ip or something but i havent checked.