WSL2는 로컬에서 이더넷 어댑터를 통해 연결이 되어있다.
-> WSL2에서 서버를 실행하면 로컬만 연결되며, 외부와는 연결되지 않는다.
WSL2내에서 서버를 동작하면 다음과 같은 과정으로 연결이 된다.
로컬의 내부IP(192.168.0.20)
-> WSL2 어댑터의 주소(172.22.192.40)
랩탑에서 자신의 로컬 환경을 외부에서 접속하려면 port forwarding작업을 통해 연결했다.
로컬의 외부IP
-> 로컬의 내부IP(192.168.0.20)
port forwarding
: 컴퓨터 네트워크에서 패킷이 라우터나 방화벽과 같은 네트워크 게이트웨이를 가로지르는 동안 하나의 IP주소와 포트 번호 결합의 통신 요청을 다른 곳으로 넘겨주는 네트워크 주소 변환의 응용이다.
따라서 WSL2에 대해서도 연결될 수 있게 port forwarding작업을 해주면 된다.
로컬의 외부IP
-> 로컬의 내부IP(192.168.0.20)
-> WSL2 어댑터의 주소(172.22.192.40)
아래의 스크립트를 *.ps1
확장자로 저장하고 윈도우 작업 스케줄러에서 트리거를 컴퓨터 시작 시로 지정하면 해결된다.
포트 설정의 경우 스크립트 내의 $ports=@(80,443,10000,3000,5000);
에서 추가/제거를 하면 된다.
$remoteport = bash.exe -c "ifconfig eth0 | grep 'inet '"
$found = $remoteport -match '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}';
if( $found ){
$remoteport = $matches[0];
} else{
echo "The Script Exited, the ip address of WSL 2 cannot be found";
exit;
}
#[Ports]
#All the ports you want to forward separated by coma
$ports=@(80,443,10000,3000,5000);
#[Static ip]
#You can change the addr to your ip config to listen to a specific address
$addr='0.0.0.0';
$ports_a = $ports -join ",";
#Remove Firewall Exception Rules
iex "Remove-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' ";
#adding Exception Rules for inbound and outbound Rules
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Outbound -LocalPort $ports_a -Action Allow -Protocol TCP";
iex "New-NetFireWallRule -DisplayName 'WSL 2 Firewall Unlock' -Direction Inbound -LocalPort $ports_a -Action Allow -Protocol TCP";
for( $i = 0; $i -lt $ports.length; $i++ ){
$port = $ports[$i];
iex "netsh interface portproxy delete v4tov4 listenport=$port listenaddress=$addr";
iex "netsh interface portproxy add v4tov4 listenport=$port listenaddress=$addr connectport=$port connectaddress=$remoteport";
}
C:\Users\kimkr\ports_wsl.ps1
ipconfig
명령어를 통해 무선 LAN어댑터 Wi-Fi의 IPv4주소로 외부에서 연결 시도하면 된다.
감사합니다!