Skip to content

Instantly share code, notes, and snippets.

@wllmsash
Last active October 18, 2024 16:44
Show Gist options
  • Save wllmsash/1636b86eed45e4024fb9b7ecd25378ce to your computer and use it in GitHub Desktop.
Save wllmsash/1636b86eed45e4024fb9b7ecd25378ce to your computer and use it in GitHub Desktop.
Assigning Static IP Addresses in WSL2

Assigning Static IP Addresses in WSL2

WSL2 uses Hyper-V for networking. The WSL2 network settings are ephemeral and configured on demand when any WSL2 instance is first started in a Windows session. The configuration is reset on each Windows restart and the IP addresses change each time. The Windows host creates a hidden switch named "WSL" and a network adapter named "WSL" (appears as "vEthernet (WSL)" in the "Network Connections" panel). The Ubuntu instance creates a corresponding network interface named "eth0".

Assigning static IP addresses to the network interfaces on the Windows host or the WSL2 Ubuntu instance enables support for the following scenarios:

  • Connect to an Ubuntu instance from the Windows host using a static IP address
  • Connect to the Windows host from an Ubuntu instance using a static IP address

This guide assumes PowerShell 7 and:

Variable Value
WSL distribution Ubuntu 20.04
WSL instance name Ubuntu-20.04
Windows host IP address 192.168.2.1
Ubuntu instance IP address 192.168.2.2
Network subnet (subnet mask) 192.168.2.0/24 (255.255.255.0)

Note It's best to pick a subnet in the private address range.

Manual Steps

Configure connectivity from the Windows host to the Ubuntu instance:

  1. Assign the Ubuntu instance IP address to the "eth0" network interface in Ubuntu (after every restart).

    sudo ip address add 192.168.2.2/24 brd + dev eth0

Configure connectivity from the Ubuntu instance to the Windows host:

  1. Add a Windows firewall allow rule (once only).

    The "vEthernet (WSL)" network interface uses the "Public" Windows network profile so all traffic from the Ubuntu instance to the host is blocked by default. Allow all inbound traffic from the "vEthernet (WSL)" network interface.

    # Requires "Run as Administrator"
    New-NetFirewallRule -Name 'WSL' -DisplayName 'WSL' -InterfaceAlias 'vEthernet (WSL)' -Direction Inbound -Action Allow

    Note Any existing rules blocking inbound traffic for applications on the Windows host will take precedence over this rule, so remove or disable these where required. Such rules can be created automatically by Windows when an application is first run. Windows shows the user a UAC modal asking for permission to create a firewall rule.

  2. Assign the Windows host IP address to the "WSL" network interface in Windows (after every restart).

    # Requires "Run as Administrator"
    New-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -IPAddress '192.168.2.1' -PrefixLength 24

PowerShell Script

All the steps above in a PowerShell script.

$WslInstanceName = 'Ubuntu-20.04'
$WindowsHostIPAddress = '192.168.2.1'
$UbuntuInstanceIPAddress = '192.168.2.2'
$SubnetMaskNumberOfBits = 24

$WslFirewallRuleName = 'WSL'
$WslNetworkInterfaceName = 'vEthernet (WSL)'
$UbuntuNetworkInterfaceName = 'eth0'

# Ensure the "vEthernet (WSL)" network adapter has been created by starting WSL.
Write-Host 'Ensure WSL network exists...'
wsl --distribution "$WslInstanceName" /bin/false
Write-Host 'WSL network exists'

# All inbound traffic from Ubuntu through Windows firewall and assign a static IP address to the "vEthernet (WSL)"
# network adapter in Windows.
Write-Host 'Configuring Windows host network...'
Start-Process 'pwsh' -Verb RunAs -Wait -ArgumentList '-ExecutionPolicy Bypass', @"
-Command & {
  Write-Host 'Checking firewall...'
  If (-Not (Get-NetFirewallRule -Name '$WslFirewallRuleName' -ErrorAction SilentlyContinue)) {
    Write-Host 'Configuring firewall...'
    New-NetFirewallRule -Name '$WslFirewallRuleName' -DisplayName '$WslFirewallRuleName' -InterfaceAlias '$WslNetworkInterfaceName' -Direction Inbound -Action Allow
    Write-Host 'Finished configuring firewall'
  }
  Else {
    Write-Host 'Already configured firewall'
  }
 
  Write-Host 'Checking network interface...'
  If (-Not (Get-NetIPAddress -InterfaceAlias '$WslNetworkInterfaceName' -IPAddress '$WindowsHostIPAddress' -PrefixLength $SubnetMaskNumberOfBits  -ErrorAction SilentlyContinue)) {
    Write-Host 'Configuring network interface...'
    New-NetIPAddress -InterfaceAlias '$WslNetworkInterfaceName' -IPAddress '$WindowsHostIPAddress' -PrefixLength $SubnetMaskNumberOfBits
    Write-Host 'Finished configuring network interface'
  }
  Else {
    Write-Host 'Already configured network interface'
  }
}
"@
Write-Host 'Finished configuring Windows host network'

# Assign a static IP address to the "eth0" network interface in Ubuntu.
Write-Host 'Configuring Ubuntu instance network...'
wsl --distribution "$WslInstanceName" --user root /bin/sh -c "if !(ip address show dev $UbuntuNetworkInterfaceName | grep -q $UbuntuInstanceIPAddress/$SubnetMaskNumberOfBits); then ip address add $UbuntuInstanceIPAddress/24 brd + dev $UbuntuNetworkInterfaceName; fi"
Write-Host 'Finished configuring Ubuntu instance network'
@Prometheus3375
Copy link

Prometheus3375 commented Oct 8, 2023

So, i have to run this script before starting any network services inside WSL?

Yes.

Also, how does shutdown if idle work?

I assume if there is no user-started processes inside WSL2 and no active terminal logged in WSL2. You can check if WSL2 is running by opening Task Manager (Ctrl+Shift+Esc) and locate process Vmmem is in the list of foreground processes. You can sort by RAM usage to quickly locate it.

image

@helkas
Copy link

helkas commented Oct 10, 2023

This still isn't working for me. I used the script. Tried doing it manually. What could I be doing wrong? I have a WSL adapter "vEthernet" on the windows side that still says 172.10.16.1, but I do not see that adapter in the adapter list in control panel. My WSL instance looks to have my newly configured IP address, but isn't pinging anything (gateway, windows box, other workloads). Any help would be greatly appreciated.

@Prometheus3375
Copy link

@helkas then disable firewall for vEthernet. Start Powershell as Admin and run next commands:

Set-NetFirewallProfile -Profile Public -DisabledInterfaceAliases 'vEthernet (WSL)'
Set-NetFirewallProfile -Profile Private -DisabledInterfaceAliases 'vEthernet (WSL)'
Set-NetFirewallProfile -Profile Domain -DisabledInterfaceAliases 'vEthernet (WSL)'

After that you will be able to ping Windows host from WSL2.

@Lauro235
Copy link

Thanks for the instructions. Would you be able to clarify how to get the information for the following.

WSL distribution | Ubuntu 20.04
WSL instance name | Ubuntu-20.04
Windows host IP address | 192.168.2.1
Ubuntu instance IP address | 192.168.2.2
Network subnet (subnet mask) | 192.168.2.0/24 (255.255.255.0)

I specifically don't know how to get my 'Windows host IP address'. I've tried typing 'ipconfig' into cmd and I'm able to see the WSL Etho ip....

A little more information regarding the initial set up would be great. Some good resources would be appreciated, as whenever I google this stuff, I'm getting jargon that is slightly different and I can't be sure if the articles are talking about the same variables and environment.

@Prometheus3375
Copy link

WSL distribution - the distribution you have installed. One of the easiest way to install is from Miscrosoft Store. This is the link to Ubintu 20.04 LTS.

WSL instance name - use wsl --list to list all present WSL distributions.
image

All others parameters are specified by the user. You need to select such IPs and subnet mask to avoid conflicts with already existing networks. The suggested values are usually fine for simple desktop/notebook setup.

@BlueTree242
Copy link

New-NetIPAddress:
Line |
15 | New-NetIPAddress -InterfaceAlias 'vEthernet (WSL)' -IPAddress '192.1 …
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| Invalid parameter InterfaceAlias vEthernet (WSL)

@angus-mcritchie
Copy link

For those still having trouble like I was after the WSL 2.0.5 update I have created a simple node script that updates your Windows host file to your current WSL IP address which works like a dream for me.

@BlueTree242
Copy link

yeah i forgot to mention i fixed this by downgrading. For the author of this script, thank you! but one day we will need to update, any solution? (that does not involve the hosts file)

@PhilipAngelinNE
Copy link

PhilipAngelinNE commented Dec 12, 2023

Slightly unrelated maybe but just throwing this out there considering recent changes Microsoft has made to WSL (not sure about details).

I duplicated my Wndows hosts file, and changed the IP on all (non-generated) entries to 0.0.0.0 in the WSL hosts file. For my case where we have Traefik (local proxy, does not use Docker), it would only listen to 127.0.0.1 specifically, meaning I couldn't connect to my virtual host if I added a port number onto it. Changing 127.0.0.1 to 0.0.0.0 in the WSL hosts file fixed that, allowing any host through.

@electropolis
Copy link

electropolis commented Jan 4, 2024

It doesn't work when the Interface receives 169.254.*.* each time and can't set the IP
But please explain what is the purpose of setting an IP on WSLHost instead of the default one? Each time this is the same NAT but using different IP Class (default is 172.x.x.x). So in my opinion it's pointless. Instead of doing this the best scenario would be bridge vSwitch with Ethernet/Wifi adapter. WSL 1 works fine but has lack of some functions.

@micheldiemer
Copy link

Anyone coming here please find below a detailed working procedure on how to do this with WSLAttachSwitch

Script : microsoft/WSL#4799 (comment)

Text : microsoft/WSL#4799 (comment)

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