Skip to content

Instantly share code, notes, and snippets.

@wllmsash
Last active April 18, 2024 23:19
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'
@penguinpages
Copy link

penguinpages commented Jul 7, 2023

Curious. I have standard windows 11 with WSL fresh install with ubuntu22.04

I typically run HyperV disabled to save RAM but just to create baseline to what you see.

BEFORE Registry changes

wsl_hyperv_internal

*Odd I have two WSL switches but both internal... and as normal.. and no idea why.. And just as important not sure any means to debug which is the one needed/used.

penguinpages@LT-WSL:/tmp$ ip ad
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: bond0: <BROADCAST,MULTICAST,MASTER> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether a2:cb:a0:d8:af:19 brd ff:ff:ff:ff:ff:ff
3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 2a:99:e3:42:3a:df brd ff:ff:ff:ff:ff:ff
4: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/ipip 0.0.0.0 brd 0.0.0.0
5: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/sit 0.0.0.0 brd 0.0.0.0
6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:3e:6f:98 brd ff:ff:ff:ff:ff:ff
    inet 172.20.137.93/20 brd 172.20.143.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::215:5dff:fe3e:6f98/64 scope link 
       valid_lft forever preferred_lft forever

After Adding registry keys

Type: String
Key: NatGatewayIpAddress
Value: 172.16.108.1

Type: String
Key: NatNetwork
Value: 172.16.108.0/24

wsl_wsl_keys

-- - Reboot - --

penguinpages@LT-WSL:~/git/gitlab/rke_poc$ ip ad
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: bond0: <BROADCAST,MULTICAST,MASTER> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether a2:be:e9:9d:33:62 brd ff:ff:ff:ff:ff:ff
3: dummy0: <BROADCAST,NOARP> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 16:bd:90:5c:c1:17 brd ff:ff:ff:ff:ff:ff
4: tunl0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/ipip 0.0.0.0 brd 0.0.0.0
5: sit0@NONE: <NOARP> mtu 1480 qdisc noop state DOWN group default qlen 1000
    link/sit 0.0.0.0 brd 0.0.0.0
6: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:15:5d:3e:67:d1 brd ff:ff:ff:ff:ff:ff
    inet 172.20.137.38/20 brd 172.20.143.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::215:5dff:fe3e:67d1/64 scope link 
       valid_lft forever preferred_lft forever
penguinpages@LT-WSL:~/git/gitlab/rke_poc$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=115 time=4.15 ms
^C
--- 8.8.8.8 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 4.151/4.151/4.151/0.000 ms
penguinpages@LT-WSL:~/git/gitlab/rke_poc$ 

So I am not sure if this is WSL vs WSL CORE switch issue..

But this speaks to issue where WSL is SOoo very cool.. but on the one aspect of networking, really needs some polish / documentation (with examples). And diagram of what its doing and tools to check /review each of the layers they built so as to debug.

@The-Monkey-King
Copy link

The-Monkey-King commented Aug 12, 2023

EDIT: I tried to change the values in Registry with Admin privs but these values popped back in. What is writing to registry to override my override?

@The-Monkey-King
Copy link

@AdilMetkali

Based on your solution I managed to have a persistent like configuration to set a static IP range even after host reboot.

Would you publish your scripts, please? I've tried the other ways and they are dead ends for me. Your method is my next attempt. Thank you.

@Prometheus3375
Copy link

Prometheus3375 commented Oct 5, 2023

PowerShell Script

New-NetFirewallRule -Name '$WslFirewallRuleName' -DisplayName '$WslFirewallRuleName' -InterfaceAlias '$WslNetworkInterfaceName' -Direction Inbound -Action Allow

If you cannot ping windows host from WSL2 even with this Firewall rule, you can try disabling Firewall for vEthernet (WSL) entirely.

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

Sources: 1, 2.


Here is also my PowerShell script I am using to configure static IP addresses:

if (!(
        ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
            [Security.Principal.WindowsBuiltInRole]::Administrator
        )
    )) {
    Start-Process pwsh "-File `"$PSCommandPath`"" -Verb RunAs
    exit
}

$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...'

# If firewall rule does not work, i.e., ping $WindowsHostIPAddress fails,
# disable firewall for the network interface entirely.
# https://superuser.com/questions/1714002/wsl2-connect-to-host-without-disabling-the-windows-firewall
# https://github.com/microsoft/WSL/issues/4585#issuecomment-1368330467
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'

@BlueTree242
Copy link

Hey, do i run the script after every restart or only one time?

@Prometheus3375
Copy link

Prometheus3375 commented Oct 8, 2023

@BlueTree242 network settings inside WSL2 reset after shutdown. Thus, you need to run the script every time you turn WSL2 on.

@BlueTree242
Copy link

@BlueTree242 network settings inside WSL2 reset after shutdown. Thus, yuo need to run the script every time you turn WSL2 on.

Is it possible to automate that? for example Windows Scheduler

@Prometheus3375
Copy link

Prometheus3375 commented Oct 8, 2023

There is some guidelines how to make network addresses persistent in the above comments, but I have not not tried it.

Is it possible to automate that? for example Windows Scheduler

Sure, it is possible to do with Windows Scheduler. Although, WSL2 shutdowns automatically if idle, and after its shutdown you need to re-run the script. I personally need WSL2 mostly for Zeppelin; I wrote a PowerShell script to start it from Windows and this script runs network configuring script before starting Zeppelin.

if (!(Is-CurrentRole-Administrator)) {
    Start-Process pwsh "-File `"$PSCommandPath`"" -Verb RunAs
    exit
}

& "D:\wsl\configure-network.ps1"

wsl /bin/sh -c "~/zeppelin-start.sh"

@BlueTree242
Copy link

There is some guidelines how to make network addresses persistent in the above comments, but I do not tried it.

Is it possible to automate that? for example Windows Scheduler

Sure, it is possible to do with Windows Scheduler. Although, WSL2 shutdowns automatically if idle, and after its shutdown you need to re-run the script. I personally need WSL2 mostly for Zeppelin, I wrote a PowerShell script to start it from Windows and this script runs network configuring script before starting Zeppelin.

So, i have to run this script before starting any network services inside WSL? Also, how does shutdown if idle work?

@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