Making Your Server on WSL2 Accessible from Your Network
If you’re running a server on WSL2 (Ubuntu) and struggling to access it from your local network, you’re not alone! By default, WSL2 operates in a virtualized network, making it inaccessible from outside your Windows host. Here’s how to fix this and make your server accessible from other devices.
Step 1: Find Your WSL2 IP Address
Open your WSL2 terminal and run:
ip addr show eth0
Look for the inet
address (e.g., 172.x.x.x
). This is your WSL2 IP.
Step 2: Set Up Port Forwarding in Windows
Since WSL2 uses a separate network, we need to forward traffic from Windows to WSL2. Open PowerShell as Administrator and run:
netsh interface portproxy add v4tov4 listenport=<your_port> listenaddress=0.0.0.0 connectport=<your_port> connectaddress=<wsl2_ip>
Replace <your_port>
with your server’s port and <wsl2_ip>
with the IP you found in Step 1.
Step 3: Allow Firewall Access
To ensure Windows doesn’t block the connection, add a firewall rule:
New-NetFirewallRule -DisplayName "WSL2 Server" -Direction Inbound -Action Allow -Protocol TCP -LocalPort <your_port>
Step 4: Access Your Server from Your Network
Now, your server should be accessible using your Windows machine’s IP instead of the WSL2 IP. You can find your Windows IP by running:
ipconfig
Look for your network adapter’s IPv4 address and use it to access your server from other devices.
Automate This Process
Since WSL2 IP changes on every restart, you may need to update port forwarding repeatedly. To automate this, create a script that retrieves the latest WSL2 IP and updates the forwarding rule accordingly.
Here’s a simple PowerShell script:
$wsl_ip = wsl -e bash -c "ip -4 addr show eth0 | grep -oP '(?<=inet\s)\d+(\.\d+){3}'"
$port = <your_port>
netsh interface portproxy delete v4tov4 listenport=$port
netsh interface portproxy add v4tov4 listenport=$port listenaddress=0.0.0.0 connectport=$port connectaddress=$wsl_ip
Run this script after each restart to ensure connectivity!
This method allows your server to be accessible on your local network while using WSL2. Let me know if you found this helpful!