Skip to content

Instantly share code, notes, and snippets.

@Alecell
Last active March 3, 2024 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Alecell/b6243922079e49e08963930bea318096 to your computer and use it in GitHub Desktop.
Save Alecell/b6243922079e49e08963930bea318096 to your computer and use it in GitHub Desktop.
LOCAL_CONNECTION_INTERFACE_NAME=""
LOCAL_CONNECTION_IPV4_SEARCH=""
# Forward WSL2 ports to host machine/platform (handles Windows Firewall)
#
# NOTE: 'iex' is a shortform for 'Invoke-Expression'
# Ports that should be forwarded to WSL2 and allowed through firewall (comma-separated)
$ports = @(8081);
# WSL IP address changes whenever WSL restarts
$wsl_ips = $(wsl hostname -I).Trim() -split '\s+';
$wsl_ip = $wsl_ips[0]
# Incoming requests from any IP should be matched
$listen_all_ips = '0.0.0.0';
if ( -Not $wsl_ip ) {
Write-Output "IP address for WSL 2 cannot be found";
exit;
}
Write-Output "WSL IP: '$wsl_ip'";
### Windows Firewall #####
$firewall_rule = "WSL2 Forwarded Ports";
$firewall_ports = $ports -join ",";
# Remove existing firewal rule (will error if not already present; can ignore)
iex "Remove-NetFireWallRule -DisplayName '$firewall_rule' ";
# Allow Expo ports through Windows Firewall
iex "New-NetFireWallRule -DisplayName '$firewall_rule' -Direction Inbound -LocalPort $firewall_ports -Action Allow -Protocol TCP;"
iex "New-NetFireWallRule -DisplayName '$firewall_rule' -Direction Outbound -LocalPort $firewall_ports -Action Allow -Protocol TCP;"
### WSL Port Proxy #####
# Show all previously proxied ports
iex "netsh interface portproxy show v4tov4"
# Configure port forwarding (via remove/add)
for ( $i = 0; $i -lt $ports.length; $i++ ) {
$port = $ports[$i];
# Remove previously proxied port
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$listen_all_ips"
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$listen_all_ips connectport=$port connectaddress=$wsl_ip"
}
# Show all newly proxied ports
iex "netsh interface portproxy show v4tov4"
cmd /c pause
const { exec } = require("child_process");
require("dotenv").config({ path: "./.env.local" });
// Executar o comando e capturar a saída
exec(
`netsh.exe interface ip show address "${process.env.LOCAL_CONNECTION_INTERFACE_NAME}"`,
(error, stdout, stderr) => {
if (error) {
console.error(`Erro ao executar o comando: ${error.message}`);
return;
}
if (stderr) {
console.error(`Erro no comando: ${stderr}`);
return;
}
// Encontrar e imprimir o endereço IPv4
const lines = stdout.split("\n");
for (const line of lines) {
if (line.includes(process.env.LOCAL_CONNECTION_IPV4_SEARCH)) {
const matches = line.match(/\b\d{1,3}(\.\d{1,3}){3}\b/g);
if (matches && matches.length > 0) {
console.log(matches[0]);
return;
}
}
}
console.log("Endereço IPv4 não encontrado.");
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment