Skip to content

Instantly share code, notes, and snippets.

@kumorikuma
Created May 11, 2023 23:42
Show Gist options
  • Save kumorikuma/b5a82f2a8f6529628210fea1d0df6cc7 to your computer and use it in GitHub Desktop.
Save kumorikuma/b5a82f2a8f6529628210fea1d0df6cc7 to your computer and use it in GitHub Desktop.
Forward traffic on a port that goes to localhost, to go to WSL instead.
#!/bin/bash
# Check if the first positional parameter is empty
if [ -z "$1" ]; then
# Assign a default value if the parameter is empty
listenport=7000
else
listenport=$1
fi
wsl_ip=$(ifconfig | grep -oP 'inet (?!127)\K[0-9.]+' | head -n 1)
echo "Forwarding data going to 0.0.0.0:$listenport to $wsl_ip:$listenport..."
/mnt/c/Windows/System32/cmd.exe /c netsh interface portproxy delete v4tov4 listenport=$listenport listenaddress=0.0.0.0 protocol=tcp
/mnt/c/Windows/System32/cmd.exe /c netsh interface portproxy add v4tov4 listenport=$listenport listenaddress=0.0.0.0 connectport=$1 connectaddress=$wsl_ip
@kumorikuma
Copy link
Author

When hosting a server on WSL, if you want to make it accessible to other computers on the local network, it's not accessible by default. We need to forward the data to WSL. This script handles that automatically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment