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'
@AdilMetkali
Copy link

AdilMetkali commented Jan 11, 2023

Hello,
Thank you for pointing me in the right direction.

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

What I did was :
I added a new IP adress (192.168.123.1) to vEthernet WSL using netsh command (Admin prompt)
I changed the wsl config by setting the "generateResolvConf" to false in /etc/wsl.conf
I deleted the generated /etc/resolv.conf and I created a new one with my DNS servers (and I used a chattr +i /etc/resolv.conf to make sure it will stay the same)
I added a new IP adress to my wsl distribution using these commands :

wsl -d $distro --user root bash -c 'ip addr flush dev eth0'
wsl -d $distro --user root bash -c 'ip addr add 192.168.123.$(shuf -i2-14 -n1)/24 brd + dev eth0'
wsl -d $distro --user root bash -c 'ip route add default via 192.168.123.1'

I persisted the changes by :

  1. Adding these commands to the root .profile :
ip addr flush dev eth0
ip addr add 192.168.123.$(shuf -i2-14 -n1)/24 brd + dev eth0
ip route add default via 192.168.123.1
  1. Creating 2 scheduled tasks :

The first one launches a wsl -d $distro --user root bash -c 'ping -c 1 -W 1 8.8.8.8' in order to initialize vEthernet WSL after reboot (should be basedon the user that has access to the distros)

The second one was done based on the "system" user to execute a netsh command to add the IP adress to vEthernet WSL, and it is executed right after the first one.

This configuration allowed me to change the IP adress to a range of my choice and have these changes persist.

Overall, it wasn't that easy to do, so let's hope Microsoft adds the customization of the IP range as a feature in future WSL2 releases.

@dxblouie
Copy link

dxblouie commented Feb 3, 2023

How i do mine with Windows 11, to grant a static IP from my home network (or in my case, a reserved IP assigned by DHCP from my main router)

in an Administrator Powershell do the following:
Run Get-NetAdapter to get your main network adapter's name in this example: "Ethernet"
Run New-VMSwitch -Name 'WSLStatic -NetAdapterName Ethernet -AllowManagementOS:$true this will create a Virtual Switch with an external network connectivity
run New-NetFirewallRule -Name 'WSL' -DisplayName 'WSL' -InterfaceAlias 'vEthernet (WSLStatic)' -Direction Inbound -Action Allow to allow communication between WSL and the host machine
Now in WSL.. set your static IP like you do any other VM, and add the following to your wsl conf ( /etc/wsl.conf )
[wsl2]
networkingMode=bridged
vmSwitch=WSLStatic

et voilà!

@eromoe
Copy link

eromoe commented Mar 7, 2023

Start-Process : 由于出现以下错误,无法运行此命令: 系统找不到指定的文件。。
所在位置 E:\Workspace\github_me\fix_wsl_ip_address.ps1:18 字符: 1
+ Start-Process 'pwsh' -Verb RunAs -Wait -ArgumentList '-ExecutionPolic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process],InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

There is no pwsh

@eromoe
Copy link

eromoe commented Mar 7, 2023

Use below code to get pwsh

winget install Microsoft.PowerShell

@penguinpages
Copy link

The function this provides is very helpful. The random 172.20.x.x segments WSL trolls to select (I would love to meet the person who thought that was a great idea), overlap with various VPN sessions, offices and customers. So its a bit of roulet if you get to function on that customer connection. They did such a great job on the new version of WSL... until this network issue.

My goal is to just pin it to 169.254.252.1 (Windows) .2 (Linux) but your script does not do a few things.

  1. Remove the bad IP from the eth0 interface which then enables IP communication
  2. set GW to this new defined IP. It binds the IP but does not re-establish a DGW
  3. Check and switch as needed to administrator mode. Though I may set this up and post how to setup to run on login with elevation

I wish the WSL team would think about these kinds of core things and how they impact people. Or post WHY they would choose such a weird IP structure, and maybe build in an option to set static .. vs this jumble of IP switching.

@rayhu
Copy link

rayhu commented May 19, 2023

Start-Process : 由于出现以下错误,无法运行此命令: 系统找不到指定的文件。。
所在位置 E:\Workspace\github_me\fix_wsl_ip_address.ps1:18 字符: 1
+ Start-Process 'pwsh' -Verb RunAs -Wait -ArgumentList '-ExecutionPolic ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Start-Process],InvalidOperationException
    + FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand

There is no pwsh

I think you need to install powershell 7, as described in the post.

@teplinsky-maxim
Copy link

I my case it was $WslInstanceName = 'Ubuntu'

@bw2k
Copy link

bw2k commented Jul 6, 2023

Thank you, very helpful info.
Based on your nice work, I wrote a script & systemd service file:

sudo bash -c 'echo \
"#!/bin/bash
# You can change this CIDR to whatever you want, e.g. 10.10.32.8/24, 192.168.1.10/24
IPADDR=172.32.24.16/24
ip address replace \$IPADDR brd + dev eth0
" > /usr/local/bin/wsl-set-ip.sh' && sudo chmod 755 /usr/local/bin/wsl-set-ip.sh

echo \
"[Unit]
Description=Set the static IP address for this WSL instance
After=network.target
[Service]
ExecStart=/usr/local/bin/wsl-set-ip.sh
[Install]
WantedBy=multi-user.target" | sudo tee /lib/systemd/system/wsl-set-static-ip.service

then enable this service:
sudo systemctl daemon-reload && sudo systemctl enable wsl-set-static-ip.service

It will automatically set the static IP address after every reboot.

BTW:
There is another way to set WSL's Default Virtual Switch IP address (aka host IP). Just Run regedit.exe as Administrator

Locate the following path
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Lxss

Change these two keys to desired value (NatNetwork must be in CIDR format)
NatGatewayIpAddress NatNetwork
Edit: don't forget to reboot

tested on Windows 11 Pro (22H2) with WSL2

@penguinpages
Copy link

Thanks for your posting. Seems like means of changing on Windows side if its just two key values is cleanest as changes to Linux side would have to be done each upgrade / new instance installed.

That being said.. you note "...Change these two keys..."

But the keys on my system do not exist

wsl_staticIP_MissingKeys

Do you mean create? And if so what value type. etc...

@bw2k
Copy link

bw2k commented Jul 7, 2023

@penguinpages
Hi, i don't know exactly why your reg key/value are different, but i do have these keys:

wsl-net-ip-reg

BTW: I'm currently using the default unmodified WSL2 virtual switch (internal network mode). You can open the Hyper-V Virtual Switch Manager (in the Hyper-V Manager) to verify.

Here is mine:
wsl-virtsw

I hope this info helps

@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