Last active
June 3, 2023 20:36
-
-
Save amane-katagiri/d76785b92ea3a7263159697bfca32e8d to your computer and use it in GitHub Desktop.
Expose server connection on WSL to LAN.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/pwsh | |
if ($args.count -eq 0){ | |
$connectport = [Microsoft.VisualBasic.Interaction]::InputBox("Input connectport (expose port on wsl)", $MyInvocation.MyCommand.Name, "8000") | |
if ($connectport.length -eq 0) { | |
Write-Error "Set connectport" -ErrorAction Stop | |
} | |
$listenport = [Microsoft.VisualBasic.Interaction]::InputBox("Input listenport (expose port on host)", $MyInvocation.MyCommand.Name, $connectport) | |
if ($listenport.length -eq 0) { | |
Write-Error "Set listenport" -ErrorAction Stop | |
} | |
} elseif ($args.count -eq 1){ | |
$connectport = $args[0] | |
$listenport = $args[0] | |
} else { | |
$connectport = $args[0] | |
$listenport = $args[1] | |
} | |
$suffix = -join (get-random -count 10 -input 0,1,2,3,4,5,6,7,8,9) | |
$wsl2Address = wsl -e hostname -I | ForEach-Object { $_.trim() } | |
New-NetFireWallRule -DisplayName "WSL 2 Firewall Unlock $suffix" -Direction Inbound -LocalPort $listenport -Action Allow -Protocol TCP | |
netsh.exe interface portproxy add v4tov4 listenaddress=* listenport=$listenport connectaddress=$wsl2Address connectport=$connectport | |
netsh.exe interface portproxy show v4tov4 | |
try { | |
Write-Host "connected $listenport -> $connectport ..." | |
Write-Host "hit Ctrl+C to close connection ..." | |
while($true) { | |
Start-Sleep 3600 | |
} | |
} finally { | |
netsh.exe interface portproxy delete v4tov4 listenport=$listenport listenaddress=* | |
Remove-NetFireWallRule -DisplayName "WSL 2 Firewall Unlock $suffix" | |
netsh.exe interface portproxy show v4tov4 | |
Write-Host "disconnected !!" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment