https://gist.github.com/wllmsash/1636b86eed45e4024fb9b7ecd25378ce
Hyper-V creates a hidden virtual switch for WSL2. In Windows, the virtual NIC vEthernet (WSL) is connected to the
switch. In WSL2 (Ubuntu), the virtual NIC eth0 is connected to the switch. Communication between the two network
endpoints happens over the switch. The virtual NICs (and possibly the switch) are ephemeral and disappear at host system
restart time. The NICs are recreated on demand when WSL2 first runs.
To use a custom static IP address we can assign each of the NICs to IP addresses on a shared subnet. It’s a good idea to
pick a subnet in the Private Address range.
The following steps help set up a fixed IP address for a WSL2 distribution from the host and a fixed IP address for the
host from WSL2, with this configuration in mind:
192.168.2.0/24Ubuntu-20.04Assign a new IP address to the virtual NIC in Windows
Assign the virtual NIC connected to WSL2 an additional IP address 192.168.2.1 (Requires “Run as Administrator”):
netsh interface ip add address "vEthernet (WSL)" 192.168.2.1 255.255.255.0
To remove in the future:
netsh interface ip delete address "vEthernet (WSL)" 192.168.2.1
Assign a new IP address to the virtual NIC in WSL2
Assign the virtual ethernet NIC an additional IP address 192.168.2.2:
sudo ip addr add 192.168.2.2/24 broadcast 192.168.2.255 dev eth0 label eth0:1
To remove in the future:
sudo ip addr del 192.168.2.201/24 dev eth0:1
Set up Windows firewall allow rule (once only)
The vEthernet (WSL) network device uses the Public Windows network profile, where all traffic is blocked by
default. We need to allow traffic from the new 192.168.2.0/24 subnet to access the host Windows machine from WSL2.
192.168.2.0/24WSL2 or similarNote: As the NICs are ephemeral these changes must be applied following every host system restart
PowerShell script to set up static IP addresses:
$WslDistribution = "Ubuntu-20.04"
$Subnet = "192.168.2" # /24
$HostAddress = "$Subnet.1"
$WslAddress = "$Subnet.2"
$BroadcastAddress = "$Subnet.255"
Start-Process pwsh -Verb RunAs -Wait -ArgumentList "-ExecutionPolicy Bypass", "-Command `"& { netsh interface ip add address \`"vEthernet (WSL)\`" $HostAddress 255.255.255.0; Write-Host -NoNewLine \`"Press any key to continue...\`"; `$Host.UI.RawUI.ReadKey(\`"NoEcho,IncludeKeyDown\`"); }`""
echo "Finished configuring host network"
wsl --distribution $WslDistribution /bin/bash -c "sudo ip addr add $WslAddress/24 broadcast $BroadcastAddress dev eth0 label eth0:1;"
echo "Finished configuring WSL2 network"