Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WSL2 - No internet connectivity. DNS Issues(Temporary failure in name resolution) #6404

Open
devshashankb opened this issue Jan 6, 2021 · 134 comments
Labels

Comments

@devshashankb
Copy link

devshashankb commented Jan 6, 2021

Environment

Windows build number: Version 10.0.18363.1256
Your Distribution version: Both Ubuntu 18.04 and Ubuntu 20.04
Whether the issue is on WSL 2 and/or WSL 1: WSL 2

Steps to reproduce

Install WSL2 with any Ubuntu distro(1804/2004) .Ping google.com or any other website. Tried on with/without VPN(Big Edge IP client).

WSL logs:
ping google.com
Temporary failure in name resolution

For sudo apt update

Err:1 http://archive.ubuntu.com/ubuntu bionic InRelease
Temporary failure resolving 'archive.ubuntu.com'
Err:2 http://security.ubuntu.com/ubuntu bionic-security InRelease
Temporary failure resolving 'security.ubuntu.com'
Err:3 http://archive.ubuntu.com/ubuntu bionic-updates InRelease
Temporary failure resolving 'archive.ubuntu.com'
Err:4 http://archive.ubuntu.com/ubuntu bionic-backports InRelease
Temporary failure resolving 'archive.ubuntu.com'
Reading package lists... Done
Building dependency tree
Reading state information... Done
All packages are up to date.
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic/InRelease Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-updates/InRelease Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://archive.ubuntu.com/ubuntu/dists/bionic-backports/InRelease Temporary failure resolving 'archive.ubuntu.com'
W: Failed to fetch http://security.ubuntu.com/ubuntu/dists/bionic-security/InRelease Temporary failure resolving 'security.ubuntu.com'
W: Some index files failed to download. They have been ignored, or old ones used instead.

Expected behavior

I should get reply to the ping. And Internet should be easily accessible from within WSL.

WSL 1 has no problem. I am able to connect to internet. When I try to use docker on WSL , it asks to upgrade to WSL2. So now i have no option. Just have to use WSL2 for docker where there is no internet connectivity

Actual behavior

image

Have looked at the solutions from other issues. None seems to works. Follows some that I have tried but it seems not to work.

  1. Added ([network]generateResolvConf = false) to wsl.conf And add nameserver 8.8.8.8 in resolv.conf

  2. Run the following powershell script

`echo "Restarting WSL Service"
Restart-Service LxssManager
echo "Restarting Host Network Service"
Stop-Service -name "hns"
Start-Service -name "hns"
echo "Restarting Hyper-V adapters"
Get-NetAdapter -IncludeHidden | Where-Object `
    {$_.InterfaceD```
escription.StartsWith('Hyper-V Virtual Switch Extension Adapter')} `
    | Disable-NetAdapter -Confirm:$False
Get-NetAdapter -IncludeHidden | Where-Object `
    {$_.InterfaceDescription.StartsWith('Hyper-V Virtual Switch Extension Adapter')} `
    | Enable-NetAdapter -Confirm:$False`

Please let me know how can i fix this issue, so i can connect to internet from my WSL

FYI Antivirus - McAffe and Windows Defender is enabled.

@PavelSosin-320
Copy link

Elementary Watson! All WSL distro are derived from the corresponding Cloud VM distros. These distros are systemd based Linux distros. The Network Manager is responsible for network configuration and every infrastructure provides the hook that configures the resolv.conf:
cat /etc/NetworkManager/dispatcher.d/hook-network-manager
#!/bin/sh

This file is part of cloud-init. See LICENSE file for license information.

This script hooks into NetworkManager(8) via its scripts

arguments are 'interface-name' and 'action'

is_azure() {
local dmi_path="/sys/class/dmi/id/board_vendor" vendor=""
if [ -e "$dmi_path" ] && read vendor < "$dmi_path"; then
[ "$vendor" = "Microsoft Corporation" ] && return 0
fi
return 1
}

is_enabled() {
# only execute hooks if cloud-init is enabled and on azure
[ -e /run/cloud-init/enabled ] || return 1
is_azure
}

if is_enabled; then
case "$1:$2" in
*:up) exec cloud-init dhclient-hook up "$1";;
*:down) exec cloud-init dhclient-hook down "$1";;
esac
fi

All this mechanism heavily relies on systemd-resolved daemon.

Without this initialization process /etc/resolv.conf is only a symbolic link pointing to /run/systemd/resolve/stub-resolv.conf created during distro installation:

No DNS servers known.

This file was automatically generated by WSL. To stop automatic generation of this file, add the following entry to /etc/wsl.conf:

[network]

generateResolvConf = false

nameserver 172.20.160.1

With generateResolvConf = false your nameserver is always 172.20.160.1
With generateResolvConf = true your nameserver can't be correctly detected without systemd-resolved daemon.
You can either add GoogleDNS 88.8.8 as a nameserver in the 1st position
or if you use "smart" WiFi router or team router with built-in DNS and DNS forwarding feature IP address of your router, 192.168.1.1 for example.

@devshashankb
Copy link
Author

With generateResolvConf = false your nameserver is always 172.20.160.1
With generateResolvConf = true your nameserver can't be correctly detected without systemd-resolved daemon.
You can either add GoogleDNS 88.8.8 as a nameserver in the 1st position
or if you use "smart" WiFi router or team router with built-in DNS and DNS forwarding feature IP address of your router, 192.168.1.1 for example.

I have tried all this but no luck. I still see the same issue

@PavelSosin-320
Copy link

Every time when WSL terminal is opened WSL generates the resolv.conf regardless of how it is configured in wsl.conf. The wsl.conf is only the link to the "real" resolv.conf file generated normally bi the systemd-resolved daemon. This is documented for such Linux distro as Ubuntu. Suse, CentOS, Debian. See for example systemd-resolved Suse and systemd-resolved Debian.
What does it mean "# Enable DNS – even though these are turned on by default, we'll specify here just to be explicit.
[network]
generateResolvConf = false" in wsl.conf if in WSL2 VM this is not a file but a symbolic link pointing to the file generated by the dedicated daemon? Is it a rudiment of WSL 1?
Why WSL 2 tries to generate the resolv.conf file if it can't do it correctly due to lack of "official" systemd?
I run WSL2 Ubuntu distro with genie and use systemd. But WSL revenges me and destroys Linux networking.

@ludzzz
Copy link

ludzzz commented Jan 19, 2021

After the last update of windows few days ago (Insider Preview build 21292.1010 ) I got the dns issue inside wsl.

a long time ago (more than 1 year ago), for the same kind of issue, I had to update the content of /etc/wsl.conf with the following.

[network]
generateResolvConf = false

I Just tried to put it at true, and it fixed the issue.
But not sure it's really something we want, to have a resolv.conf generated.

@jnguyen1098
Copy link

Also got this issue from the recent 1010 update.

@PavelSosin-320
Copy link

I run Windows 10 Pro Insider preview build 212921010
I am afraid that resolv.conf generation for WSL is too much simplified to work in the complex networking environment. I looked into the Linux log what Linux resolve daemon does in Linux: it checks Network interface statuses and route ability before pushing something into the file on which /etc/resolv link points. It is not helpful to use DNS that is not reachable itself. DNS itself must be functional. It allows multiple nameservers via multiple interfaces. etc. It doesn't assume that the computer is attached to the Internet Laptop can be connected to the different WiFi networks managed by different providers. Also, preferable DNS is different.
Every time when Driver emits a status event daemon has to manipulate with DNS list.
In my default distro Ubuntu 20.10
I use the "static" DNS address 192.168.1.1 because if I can't reach my router I can't reach DNS and any other site.
Inside my router, I have both Dynamic DNS and DNS forwarding enabled. It helps because the router has its own IPV6 DHCP WAN address gotten from ISP
My preferable DNS is ping dns9.quad9.net
PING dns9.quad9.net (9.9.9.9) 56(84) bytes of data.
64 bytes from dns9.quad9.net (9.9.9.9): icmp_seq=1 ttl=54 time=20.5 ms
64 bytes from dns9.quad9.net (9.9.9.9): icmp_seq=2 ttl=54 time=13.1 ms
and not my ISP or Google:
ping dns.google
PING dns.google (8.8.8.8) 56(84) bytes of data.
64 bytes from dns.google (8.8.8.8): icmp_seq=1 ttl=113 time=72.3 ms
and not DNS got from my ISP
ping 172.28.80.1
PING 172.28.80.1 (172.28.80.1) 56(84) bytes of data.
--- 172.28.80.1 ping statistics ---
14 packets transmitted, 0 received, 100% packet loss, time 13558ms
It works stably because I trust in the Router's OpenWRT DNS logic and bypass all suspicious or unstable DNS addresses.

@jnguyen1098
Copy link

After the last update of windows few days ago (Insider Preview build 21292.1010 ) I got the dns issue inside wsl.

a long time ago (more than 1 year ago), for the same kind of issue, I had to update the content of /etc/wsl.conf with the following.

[network]
generateResolvConf = false

I Just tried to put it at true, and it fixed the issue.
But not sure it's really something we want, to have a resolv.conf generated.

I didn't see this reply. I did this and it also fixed my recent issue.

@PavelSosin-320
Copy link

PavelSosin-320 commented Jan 26, 2021

Resolv.conf generation in the current implementation is a useless and harmful feature in the most cases. Even Chrome knows to test DNS availability 1st according to "DNS PROBE ERROR" appears in the case of connectivity issues. Google shows a long list of The "best DNS determination" tools. The correct DNS selection depends on the status of network interfaces and how the host is connected to the global internet infrastructure. Also, DNS protocol can vary from UDP to DOH The best choice is always the DNS that is connected to the LAN itself. IT is 99.9% available and can be easily rebooted. Its status can be easily tested using nslookup 8.8.8.8 - must return name = dns.google .

@OneBlue
Copy link
Collaborator

OneBlue commented Jan 29, 2021

Thanks for reporting the issue @devshashankb .

Can you please follow these instructions and share the script output, and both wsl.etl and packets.etl ?

@eromoe
Copy link

eromoe commented Feb 4, 2021

I have this issue happened recently too .
Edit /etc/wsl.conf with

[network]
generateResolvConf = false

and change /etc/resolve.conf doesn't solve my problem .

ifconfig show nothing.

@PavelSosin-320
Copy link

"Temporary failure in name resolution" looks like a message coming from DNS client or server.
If ifconfig -a, ip -a in Ubuntu shows nothing then the networking doesn't work at all and configured in resolv.conf DNS is not reachable. But if you can look at ls a- /etc/resolv.conf - and cat /etc/resolv.conf output and check that the /etc/resolv.conf is a link and you can ping the 1st nameserver in the resolv.conf you can save your time. The DNS must be accessible via VM's eth0 interface and be usable. To test the DNS you can try nsllookup your-site-url your-configured-DNS from the Windows command line.
P.S. There is no reason to trust in your ISP DNS. There are many alternative DynDNS providers with better maintenance, performance, and security starting from 8.8..8.8.

@PavelSosin-320
Copy link

@devshashankb I am afraid you are 100% correct and WSL team is 100% not :(. In the recent and most useful Linux distros DNS resolution is so tightly coupled with systemd mechanism, resolved service, and dbus service that any alternative solution is not possible. The provided by Debian, Ubuntu, and Fedora distro lines services are perfectly tuned to the modern networking and cloud computing environment. The old Windows-like solution has stopped working without mitigation using Router configuration that enables DynDNS and other than UDP protocols usage.
I start my most useful distros Ubuntu 20.10 and Fedora 33 with systemd support and have
In Ubuntu:
$ systemd-resolve 9.9.9.9
9.9.9.9: dns9.quad9.net
In Fedora - similar
systemd-resolve 9.9.9.9
9.9.9.9: dns9.quad9.net -- link: eth0

-- Information acquired via protocol DNS in 12.8ms.
-- Data is authenticated: no

But my /etc/resolv.conf link is overridden every wsl "login". I have to re-create it manually every time. Otherwise, these systemd based Linux distros can't access the internet, i.e cloud services, repositories,etc. deployed globally Every attempt to resolve DNS names using "old static DNS servers" results in a "temporary" DNS resolution error, as expected.

@PavelSosin-320
Copy link

Hey, I succeeded to run systemd-resolved service manually and it found 3 critical issues:

  1. Not all protocols used in DNS resolution are passed from WSL VM to the probed DNS server. But this is OK. resolved knows how to recover.
  2. Generated /etc/hosts file contained invalid character in the line 7 - it affects local routers communication for the address starting from 192.
  3. /etc/resolv.conf is re-created every distro start. Since /etc/resolv.conf "created manually" has the highest priority I have to remove it every time.
    Everything else works OK and provides optimized DNS resolution.

@PavelSosin-320
Copy link

After a few weeks of experience with the real-world Linux distro used as a WSL image that managed by systemd, I found that if the original distro was systemd-based then all games with /etc/resolv.conf affect nothing. Every program built with the networking libraries for these distro establishes IPC connection with systemd-resolve using D-Bus and the DNS resolver daemon solves for the "client" program all issues related to DNS using its own configuration: interface to communicate with DNS, protocol, possible delegation to the globally deployed dDNS service, etc. Everything works because the modern Internet infrastructure is virtually unbreakable. When I run OCI containers in my distro the running container gets the correct resolv.conf content as magic.

@ludzzz
Copy link

ludzzz commented Feb 19, 2021

I didn't even know we could run other distrib than the one given by the store.
I will try it.
a bit out of the subject, @PavelSosin-320 did you find some pro and con (apart of the network ) to use a real-world Linux distro

@PavelSosin-320
Copy link

PavelSosin-320 commented Feb 19, 2021 via email

@K2ouMais
Copy link

Is there a chance that you are getting the DNS resolution error, while on a VPN?

Because this is exactly the same problem I am having for some months now and because I dont have admin rights on my working maschine I am not able to make it work.

It have been 4-5 months now without using my WSL2 on a VPN.

@PavelSosin-320
Copy link

Some reaction from Microsoft?
WSL ignores
[network]
generateResolvConf = false
and generates resolv.conf containing wrong nameserver IP address. The generated IP is that the ISP provides via Network bridge ( modem or combo ). If the local network is managed by a router the correct primary nameserver must be the IP of the Router's nameserver that configured in the router, VPN-provided DNS or Corporate DNS depends on Networking scenario in the LAN .In many cases, this DNS is the least stable of all available. My luck is that I run WSL distros with systemd and resolve daemon and in this scenario /etc/resolv.conf is only a link to the generated by resolve daemon stub. In systemd-based Linux distros /etc/resolv.conf is not the primary nameserver source. The nameserver value in the WSL generated resolv.conf is silently ignored and everything works like swiss watch.

@K2ouMais
Copy link

K2ouMais commented Feb 23, 2021

@PavelSosin-320

You have to change sudo nano /etc/wsl.conf.

[network]
generateResolvConf = false

After that go to sudo nano /etc/resolv.conf delete everything there and put your desired nameservers there:

nameserver 1.1.1.1

After that in Powershell type wsl --shutdown.

Now your resolv.conf will be the same.

@astroboylrx
Copy link

@K2ouMais

I did exactly that. Although WSL2 won't generate /etc/resolv.conf anymore, WSL2 deletes the file every time when I restart it (so no nameserver at all). Do you happen to know what is happening? Thanks in advance.


Edition Windows 10 Home Insider Preview
Version Dev
OS build 21322.1000

@K2ouMais
Copy link

K2ouMais commented Mar 1, 2021

It deletes the file? That never happened to me.

It must be something else you have setup, to that to happen.

@Vifier-Lockla
Copy link

Vifier-Lockla commented Mar 1, 2021

I'm working with WSL2 and Ubuntu 20.04LTS

Ok try this solution (it works for me) :

Create /etc/wsl.conf as explained before with that :

[network]
generateResolvConf = **false**

1 . Rename link /etc/resolv.conf :
> sudo mv /etc/resolv.conf /etc/resolv.conf.old

2 . Create and edit new resolv.conf file (not a link) :
> sudo vi /etc/resolv.conf

and just add this line (indicate your livebox gateway address / (orange for me)) :

nameserver 192.168.1.1

3 . Don't forget to change authorization :

> sudo chmod 777 /etc/resolv.conf

You should see that :
image
image

4 . close console and reopen it. just type :
exit

5 . Try to update linux (sudo apt update) to check network connection and .... it works well (not before procedure).

I hope enjoy for you too !

Edition Windows 10 Professional 20H2
Insider - Canal release preview
OS build 19042.844

@margarineHound
Copy link

I'm working with WSL2 and Ubuntu 20.04LTS

Ok try this solution (it works for me) :

Create /etc/wsl.conf as explained before with that :

[network]
generateResolvConf = **false**

1 . Rename link /etc/resolv.conf :
> sudo mv /etc/resolv.conf /etc/resolv.conf.old

2 . Create and edit new resolv.conf file (not a link) :
> sudo vi /etc/resolv.conf

and just add this line (indicate your livebox gateway address / (orange for me)) :

nameserver 192.168.1.1

3 . Don't forget to change authorization :

> sudo chmod 777 /etc/resolv.conf

You should see that :
image
image

4 . close console and reopen it. just type :
exit

5 . Try to update linux (sudo apt update) to check network connection and .... it works well (not before procedure).

I hope enjoy for you too !

Edition Windows 10 Professional 20H2
Insider - Canal release preview
OS build 19042.844

I tried this unforunately it doesn't work for me

@PavelSosin-320
Copy link

PavelSosin-320 commented Mar 8, 2021

Ubuntu, CentOS, Fedora,Suse are systemd-based distros today. Most of utilities and applications are written in assumption that the distro is booted by systemd, NetworkManager and Resolved services have done their job and serve everybody via D-Bus. The /etc/resolv.conf link only points to resolv.conf stub and the content of /etc/resolv is not so important, Configuration of NM and Resolved consists of dozens of lines and allows to config networking in the very complex setups. /etc/resolv.conf allows to configure network only if the computer is attached to the wall using a basic modem. But it is relikt setup today. What do you expect?
And finally: WSL doesn't wakeup WiFi network alone. The "manual" wakeup using ping from the Command prompt is needed!

@PavelSosin-320
Copy link

How it works in my setup with genie and systemd:

  1. Wakeup the machine WiFi using ping from the Command prompt - WSL doesn't do it alone. You can wait forever.
  2. Follow Check Linux network interface status
  3. Check that Network is ready
    systemctl status systemd-networkd
    ● systemd-networkd.service - Network Service
    Loaded: loaded (/usr/lib/systemd/system/systemd-n
    etworkd.service; enabled; vendor preset: disabled)
    Active: active (running) since Tue 2021-03-09 08:18:55 IST; 12min ago
    TriggeredBy: ● systemd-networkd.socket
    Docs: man:systemd-networkd.service(8)
    Main PID: 24 (systemd-network)
    Status: "Processing requests..."
    Tasks: 1 (limit: 14367)
    Memory: 3.2M
    CGroup: /system.slice/systemd-networkd.service
    └─24 /usr/lib/systemd/systemd-networkd
  4. Check that you are connected in the log
    systemctl status systemd-networkd
    ● systemd-networkd.service - Network Service
    Loaded: loaded (/usr/lib/systemd/system/systemd-n
    etworkd.service; enabled; vendor preset: disabled)
    Active: active (running) since Tue 2021-03-09 08:18:55 IST; 12min ago
    TriggeredBy: ● systemd-networkd.socket
    Docs: man:systemd-networkd.service(8)
    Main PID: 24 (systemd-network)
    Status: "Processing requests..."
    Tasks: 1 (limit: 14367)
    Memory: 3.2M
    CGroup: /system.slice/systemd-networkd.service
    └─24 /usr/lib/systemd/systemd-networkd

Mar 09 08:18:55 MSI-wsl systemd-networkd[24]: /usr/lib/systemd/network/80-container-ve.network:23: IPMasquerade=yes is deprecated, and
it is handled as "ipv4" instead of "both". Please use "ipv4" or "both".
Mar 09 08:18:55 MSI-wsl systemd-networkd[24]: /usr/lib/systemd/network/80-container-vz.network:22: IPMasquerade=yes is deprecated, and
it is handled as "ipv4" instead of "both". Please use "ipv4" or "both".
Mar 09 08:18:55 MSI-wsl systemd-networkd[24]: /usr/lib/systemd/network/80-vm-vt.network:22: IPMasquerade=yes is deprecated, and it is handled
as "ipv4" instead of "both". Please use "ipv4" or "both".
Mar 09 08:18:55 MSI-wsl systemd-networkd[24]: eth0: Gained IPv6LL
Mar 09 08:18:55 MSI-wsl systemd-networkd[24]: Enumeration completed
Mar 09 08:18:55 MSI-wsl systemd[1]: Started Network Service.
Mar 09 08:20:19 MSI-wsl systemd-networkd[24]: eth0: Lost carrier
Mar 09 08:20:23 MSI-wsl systemd-networkd[24]: eth0: Gained carrier
Mar 09 08:20:28 MSI-wsl systemd-networkd[24]: eth0: Lost carrier
Mar 09 08:20:30 MSI-wsl systemd-networkd[24]: eth0: Gained carrier

If the last record says "eth0: Gained network you are OK.

@PavelSosin-320
Copy link

If somebody still has DNS resolution issues than open \wsl\Fedora34\etc\systemd\resolved.conf file using any editor that preserves Linux EOL, read documentation inside (5 min), and configure DNS resolution according to guidelines and his/her desire.

@hazardland
Copy link

hazardland commented Mar 30, 2021

It seems lounching VSCode daemon messes things up

Setup below helped me, thanks guys:

  1. /etc/wsl.conf
[network]
generateResolvConf = false
  1. Shutdown wsl
wsl --shutdown
  1. Start wsl, delete /etc/resolv.conf symbolic link and create a file instead:
    /etc/resolv.conf
nameserver 8.8.8.8

@ymongo
Copy link

ymongo commented Oct 11, 2022

Fix for VPN:

  1. Find out nameserver with windows powershell (during VPN Session and without) using nslookup
  2. USe sudo touch /etc/wsl.conf and sudo vim /etc/wsl.conf to add:
[network]                                                                        
generateResolvConf = false
  1. Restart wsl (Windows powershell) using wsl --shutdown
  2. Open WSL and remove using rm -f /etc/resolv.conf
  3. Add new file sudo touch /etc/resolv.conf and sudo vim /etc/resolv.conf with:
nameserver X.X.X.X

nameserver Y.Y.Y.Y
  1. Restart wsl (Windows powershell) using wsl --shutdown
  2. Open WSL and remove using wget google.com and test some you corporate domain.

Worked form me: get name server via nslookup, in resolv.conf options rotate and options timeout:1 on top, then all my possible nameservers below

@mjaric
Copy link

mjaric commented Oct 14, 2022

For me, fix was rather simple, Network mode was set to public, and box "Block all incoming connections, including those in the list of allowed apps." was ticked. After it is unchecked, even auto-generated resolved.conf worked form me.

@oceangravity
Copy link

This solved my issue

1 . Rename link /etc/resolv.conf :
> sudo mv /etc/resolv.conf /etc/resolv.conf.old

Doing this and changing permission to 777 worked for me

Thanks!

@PunGy
Copy link

PunGy commented Feb 1, 2023

I've tried every enlisted here solution - nothing helps. The only solution which is helped me is this one: https://learn.microsoft.com/en-us/windows/wsl/troubleshooting?source=recommendations#wsl-has-no-network-connectivity-once-connected-to-a-vpn

Generally, you just get the list of DNS servers used by your VPN via ipconfig.exe /all, and then copy-paste all these IPs from the DNS section to the /etc/resolv.conf. Restarting WSL and everything is working!

@K2ouMais
Copy link

K2ouMais commented Feb 1, 2023

Guys, just try wsl-vpnkit.

At least I can with it use WSL while on VPN.

https://crapts.org/2022/05/17/wsl2-network-connectivity-when-using-a-vpn/

@BertBR
Copy link

BertBR commented Mar 2, 2023

Any solution for that ? I've tried all these sugestions above but nothing works.

@mfabbri
Copy link

mfabbri commented Mar 7, 2023

My 2 cents
No one of the suggestions mentioned in this thread worked for me, probably I'm an edge case scenario as I'm using 2 VPN clients.
But one simple change did the trick: thanks to Alistar Young
https://randombytes.substack.com/p/bridged-networking-under-wsl
If you have this recent WSL version

>wsl --version
Versione WSL: 1.1.3.0
Versione kernel: 5.15.90.1
Versione WSLg: 1.0.49
Versione MSRDC: 1.2.3770
Versione Direct3D: 1.608.2-61064218
Versione DXCore: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
versione Windows: 10.0.22621.1265

just create a bridged Hyper-V adapter and add these lines to .wslconfig

[wsl2]
networkingMode = bridged
vmSwitch = <bridgeAdapterName>

The properties are NOT documented yet (https://learn.microsoft.com/en-us/windows/wsl/wsl-config), but it made my day.

@kntkymt
Copy link

kntkymt commented Mar 28, 2023

In my environment, I found a 3rd party security software (e. g. ESET McAffe ) blocked WSL from working DNS. Only disabling a firewall of a security software works fine.

@jerrychong25
Copy link

In my case, I've disabled Internet Protocol Version 6 (TCP/IPv6) in WLAN Properties of Network Connections Settings.

Configuration Screenshot:

1

Ping GitHub.com Successfully Screenshot:

2

Source:
https://unix.stackexchange.com/a/628767/338681

@crystalthoughts
Copy link

How is this still an issue?

@dag03tsc
Copy link

dag03tsc commented Jun 26, 2023

How is this still an issue?

@crystalthoughts, this does not seem to be a single issue, but a collection of them, some already fixed, some not. Each and every one of my setups has performed fine since months ago, but there seem to be some specific setups still broken depending on the installed SW (VPN, AV, etc.) or network settings.

@D0cNet
Copy link

D0cNet commented Jun 27, 2023

These steps helped me (the answer by Gamepad.Coder on this question ):

  1. Open Powershell or Cmd as Administrator
    and run each of these commands:
wsl --shutdown
netsh winsock reset
netsh int ip reset all
netsh winhttp reset proxy
ipconfig /flushdns
  1. Hit the Windows Key,
    type Network Reset,
    hit enter.

You should see this window. Click "Reset now".

image

  1. Restart Windows

This worked for me no problem!

@Maryam-bit
Copy link

I Just tried to put it at true, and it fixed the issue. But not sure it's really something we want, to have a resolv.conf generated.

@ludzzz this resolved my issue , thanks

@craigloewen-msft
Copy link
Member

Hi folks, we have put out a new update that aims to address networking issues in WSL. In your .wslconfig file you can set experimental.networkingMode=mirrored, as well as some other key settings that should improve your network compatibility! Please try them out and let us know what you think.

More info on this release and the changes can be found here in the blog post.

Please note: You need to be on a Windows Insiders version to use the new networking settings (Any channel of Windows Insiders will do, including release preview). If you see the "These are not supported" messages it means that your current Windows version doesn't have support, and you will need to upgrade. These features will eventually be coming to Windows 11 22H2.

@nguyenntt97
Copy link

These steps helped me (the answer by Gamepad.Coder on this question ):

  1. Open Powershell or Cmd as Administrator
    and run each of these commands:
wsl --shutdown
netsh winsock reset
netsh int ip reset all
netsh winhttp reset proxy
ipconfig /flushdns
  1. Hit the Windows Key,
    type Network Reset,
    hit enter.

You should see this window. Click "Reset now".
image

  1. Restart Windows

This worked for me no problem!

This worked for me too, Windows 10 Build 19045, WSL2, Ubuntu 22.04

@craigloewen-msft
Copy link
Member

These new networking features are now available on the latest version of Win11 22H2!

Please make sure you're on the latest build to get these features, you can do that by clicking "Check for Updates" in Windows settings. You can check you have the right build by either ensuring you have KB5031354 installed, or run cmd.exe /c ver and ensure that your build number is 22621.2428 or higher (Including the minor build number which is after the . as this was a backport!)

@NeroProtagonist
Copy link

Added

[experimental]
networkingMode=mirrored

to my .wslconfig and DNS is now working.
My dns config is custom nameserver and search options in /etc/resolv.conf

@dag03tsc
Copy link

dag03tsc commented Nov 22, 2023

I tried the new mirrored networking mode, but Docker Desktop crashed after its first reboot, though everything else seemed to work properly.

After that, I performed the factory reset encouraged by Docker Desktop and it worked fine until the next engine restart or system reboot instead. Then, the engine startup crashed once again, and so on. Furthermore, the Kubernetes feature did not even initialise for the first time, no matter how many restarts, factory resets or reboots I performed.

Once .wslconfig became saved with the networking mode reverted to NAT, things went back to normal with no restart, factory reset, or reboot at all.

Bearing in mind everything seemed to work flawlessly and blazing fast, but Docker Desktop, I'm not really sure whether this was a compatibility issue on the WSL side or on the Docker side instead.

@craigloewen-msft, I'll be glad to provide any log you esteem necessary to ease the addressing of this issue if it is on the WSL side indeed, though I guess this could be somehow related to both #10494 and Docker#13686

Edit: Everything working flawlessly and blazing fast with Docker Desktop >=4.26.0, which added support for the new mirrored mode! 🥳🚀

@Waghabond
Copy link

Waghabond commented Jan 24, 2024

Added

[experimental]
networkingMode=mirrored

to my .wslconfig and DNS is now working. My dns config is custom nameserver and search options in /etc/resolv.conf

Mirrored mode is definitely the way to go! For those who would like to understand how it works/why it's better: here's a decent article+video on it, and here's a link to the documentation. Mirrored mode has now moved from being an experimental feature to being a stable feature under the [wsl2] section. Another thing people should probably turn on for DNS issues caused by VPNs is the new dnsTunneling feature which communicates directly to the windows host to resolve hostnames instead of sending network packets which can be blocked or interfered with by VPNs. So DNS tunneling should help avoid network issues in WSL caused by VPNs.

@gethari
Copy link

gethari commented Feb 19, 2024

This worked for me

sudo rm /etc/resolv.conf
sudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'
sudo bash -c 'echo "[network]" > /etc/wsl.conf'
sudo bash -c 'echo "generateResolvConf = false" >> /etc/wsl.conf'
sudo chattr +i /etc/resolv.conf

Source: https://askubuntu.com/a/1398053

@renepanke
Copy link

This worked for me

sudo rm /etc/resolv.conf
sudo bash -c 'echo "nameserver 8.8.8.8" > /etc/resolv.conf'
sudo bash -c 'echo "[network]" > /etc/wsl.conf'
sudo bash -c 'echo "generateResolvConf = false" >> /etc/wsl.conf'
sudo chattr +i /etc/resolv.conf

Source: https://askubuntu.com/a/1398053

I can confirm. This worked for me as well.

@josemrfl
Copy link

josemrfl commented Mar 7, 2024

These steps helped me (the answer by Gamepad.Coder on this question ):

  1. Open Powershell or Cmd as Administrator
    and run each of these commands:
wsl --shutdown
netsh winsock reset
netsh int ip reset all
netsh winhttp reset proxy
ipconfig /flushdns
  1. Hit the Windows Key,
    type Network Reset,
    hit enter.

You should see this window. Click "Reset now".
image

  1. Restart Windows

This worked for me no problem!

This worked for me too, Windows 10 Build 19045, WSL2, Ubuntu 22.04

This solution worked for me. But when I disconnect from the VPN and connect again, I have the same problem again and I have to repeat the whole process again and restart. Has it happened to anyone else?

@Roemer
Copy link

Roemer commented Mar 11, 2024

We suffer from the same issue.

WSL2 looses network connectivity on certain cases like:

  • Windows goes to sleep
  • VPN client crashes or the lease finishes
  • Network adapter is changed (Wifi to LAN or the other way)

What we found out is that in case where the connectivity is lost, there are additional routes in the routing table in Windows attached to the VPN Adapter with the destination of the WSL Adapter (or more, the IP-Range of the WSL Adapter). If we remove this routes, the connectivity comes back immediately.

Here is a script that lists all relevant routes regarding WSL (adjust the <your adapter identifer> for your VPN adapter). For us, when there are any routes in the section Routes for the VPN Adapter, WSL is offline. And if we delete all these routes, WSL2 gets connectivity back immediately.

function main {

    $adapterVpn = Get-NetAdapter -InterfaceDescription "<your adapter identifer>"
    $adapterWsl = Get-NetAdapter -Name "vEthernet (WSL)"
    $ipInfoVpn = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapterVpn.ifIndex
    $ipInfoWsl = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapterWsl.ifIndex
    $wslCidr = "$($ipInfoWsl.IPAddress)/$($ipInfoWsl.PrefixLength)"

    $ipInfoWslVm = wsl -- ip -o -4 -json addr list eth0 `
        | ConvertFrom-Json `
        | %{ $_.addr_info.local } `
        | ?{ $_ }

    Write-Host "=== VPN (ID $($adapterVpn.ifIndex)) ==="
    Write-Host "IP: $($ipInfoVpn.IPAddress)"
    Write-Host
    Write-Host "=== WSL Adapter (ID $($adapterWsl.ifIndex)) ==="
    Write-Host "IP: $($ipInfoWsl.IPAddress)"
    Write-Host "MASK: $(convert-cidr-to-string -cidr $ipInfoWsl.PrefixLength) (/$($ipInfoWsl.PrefixLength))"
    Write-Host
    Write-Host "=== WSL VM ==="
    Write-Host "IP: $($ipInfoWslVm)"
    Write-Host

    $routesWsl = Get-NetRoute -AddressFamily IPv4 -InterfaceIndex $adapterWsl.ifIndex
    $routesVpn = Get-NetRoute -AddressFamily IPv4 -InterfaceIndex $adapterVpn.ifIndex

    Write-Host "=== Routes for the WSL Adapter ==="
    $routesWsl | Format-Table `
        @{L=Dst Address;E={convert-cidr-range-to-address-string $_.DestinationPrefix}}, `
        @{L=Dst Mask;E={convert-cidr-range-to-mask-string $_.DestinationPrefix}}, `
        @{L="Metric";E={$_.InterfaceMetric + $_.RouteMetric}}, `
        NextHop

    Write-Host "=== Routes for the VPN Adapter ==="
    $routesVpn | Where-Object { is-cidr-in-cidr-range $wslCidr $_.DestinationPrefix } | Format-Table `
        @{L=Dst Address;E={convert-cidr-range-to-address-string $_.DestinationPrefix}}, `
        @{L=Dst Mask;E={convert-cidr-range-to-mask-string $_.DestinationPrefix}}, `
        @{L="Metric";E={$_.InterfaceMetric + $_.RouteMetric}}, `
        NextHop
}

function convert-cidr-to-string {
    param($cidr)
    $shift = 64 - $cidr
    [System.Net.IPAddress]$subnet = 0
    $subnet = [System.Net.IPAddress]::HostToNetworkOrder([int64]::MaxValue -shl $shift)
    return $subnet.IPAddressToString
}

function convert-cidr-range-to-address-string {
    param($cidrNotation)
    return $cidrNotation.split('/')[0]
}

function convert-cidr-range-to-mask-string {
    param($cidrNotation)
    return convert-cidr-to-string -cidr $cidrNotation.split('/')[1]
}

function is-cidr-in-cidr-range {
    param (
        [string] $cidrNotationRange,
        [string] $cidrCurrent
    )

    $ip = convert-cidr-range-to-address-string $cidrCurrent

    $min, $max = cidr-to-ip-range $cidrNotationRange
    return ([version]$min) -le ([version]$ip) -and ([version]$ip) -le ([version]$max)
}

function cidr-to-ip-range {
    param (
        [string] $cidrNotation
    )

    $addr, $maskLength = $cidrNotation -split '/'
    [int]$maskLen = 0
    if (-not [int32]::TryParse($maskLength, [ref] $maskLen)) {
        throw "Cannot parse CIDR mask length string: '$maskLen'"
    }
    if (0 -gt $maskLen -or $maskLen -gt 32) {
        throw "CIDR mask length must be between 0 and 32"
    }
    $ipAddr = [Net.IPAddress]::Parse($addr)
    if ($ipAddr -eq $null) {
        throw "Cannot parse IP address: $addr"
    }
    if ($ipAddr.AddressFamily -ne [Net.Sockets.AddressFamily]::InterNetwork) {
        throw "Can only process CIDR for IPv4"
    }

    $shiftCnt = 32 - $maskLen
    $mask = -bnot ((1 -shl $shiftCnt) - 1)
    $ipNum = [Net.IPAddress]::NetworkToHostOrder([BitConverter]::ToInt32($ipAddr.GetAddressBytes(), 0))
    $ipStart = ($ipNum -band $mask)
    $ipEnd = ($ipNum -bor (-bnot $mask))

    # return as tuple of strings:
    ([BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($ipStart)) | ForEach-Object { $_ } ) -join '.'
    ([BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($ipEnd)) | ForEach-Object { $_ } ) -join '.'
}

main

@erikrok
Copy link

erikrok commented Jul 31, 2024

> We suffer from the same issue.

WSL2 looses network connectivity on certain cases like:

  • Windows goes to sleep
  • VPN client crashes or the lease finishes
  • Network adapter is changed (Wifi to LAN or the other way)

What we found out is that in case where the connectivity is lost, there are additional routes in the routing table in Windows attached to the VPN Adapter with the destination of the WSL Adapter (or more, the IP-Range of the WSL Adapter). If we remove this routes, the connectivity comes back immediately.

Here is a script that lists all relevant routes regarding WSL (adjust the <your adapter identifer> for your VPN adapter). For us, when there are any routes in the section Routes for the VPN Adapter, WSL is offline. And if we delete all these routes, WSL2 gets connectivity back immediately.

function main {

 $adapterVpn = Get-NetAdapter -InterfaceDescription "<your adapter identifer>"
 $adapterWsl = Get-NetAdapter -Name "vEthernet (WSL)"
 $ipInfoVpn = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapterVpn.ifIndex
 $ipInfoWsl = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapterWsl.ifIndex
 $wslCidr = "$($ipInfoWsl.IPAddress)/$($ipInfoWsl.PrefixLength)"

 $ipInfoWslVm = wsl -- ip -o -4 -json addr list eth0 `
     | ConvertFrom-Json `
     | %{ $_.addr_info.local } `
     | ?{ $_ }

 Write-Host "=== VPN (ID $($adapterVpn.ifIndex)) ==="
 Write-Host "IP: $($ipInfoVpn.IPAddress)"
 Write-Host
 Write-Host "=== WSL Adapter (ID $($adapterWsl.ifIndex)) ==="
 Write-Host "IP: $($ipInfoWsl.IPAddress)"
 Write-Host "MASK: $(convert-cidr-to-string -cidr $ipInfoWsl.PrefixLength) (/$($ipInfoWsl.PrefixLength))"
 Write-Host
 Write-Host "=== WSL VM ==="
 Write-Host "IP: $($ipInfoWslVm)"
 Write-Host

 $routesWsl = Get-NetRoute -AddressFamily IPv4 -InterfaceIndex $adapterWsl.ifIndex
 $routesVpn = Get-NetRoute -AddressFamily IPv4 -InterfaceIndex $adapterVpn.ifIndex

 Write-Host "=== Routes for the WSL Adapter ==="
 $routesWsl | Format-Table `
     @{L=Dst Address;E={convert-cidr-range-to-address-string $_.DestinationPrefix}}, `
     @{L=Dst Mask;E={convert-cidr-range-to-mask-string $_.DestinationPrefix}}, `
     @{L="Metric";E={$_.InterfaceMetric + $_.RouteMetric}}, `
     NextHop

 Write-Host "=== Routes for the VPN Adapter ==="
 $routesVpn | Where-Object { is-cidr-in-cidr-range $wslCidr $_.DestinationPrefix } | Format-Table `
     @{L=Dst Address;E={convert-cidr-range-to-address-string $_.DestinationPrefix}}, `
     @{L=Dst Mask;E={convert-cidr-range-to-mask-string $_.DestinationPrefix}}, `
     @{L="Metric";E={$_.InterfaceMetric + $_.RouteMetric}}, `
     NextHop
}

function convert-cidr-to-string {
 param($cidr)
 $shift = 64 - $cidr
 [System.Net.IPAddress]$subnet = 0
 $subnet = [System.Net.IPAddress]::HostToNetworkOrder([int64]::MaxValue -shl $shift)
 return $subnet.IPAddressToString
}

function convert-cidr-range-to-address-string {
 param($cidrNotation)
 return $cidrNotation.split('/')[0]
}

function convert-cidr-range-to-mask-string {
 param($cidrNotation)
 return convert-cidr-to-string -cidr $cidrNotation.split('/')[1]
}

function is-cidr-in-cidr-range {
 param (
     [string] $cidrNotationRange,
     [string] $cidrCurrent
 )

 $ip = convert-cidr-range-to-address-string $cidrCurrent

 $min, $max = cidr-to-ip-range $cidrNotationRange
 return ([version]$min) -le ([version]$ip) -and ([version]$ip) -le ([version]$max)
}

function cidr-to-ip-range {
 param (
     [string] $cidrNotation
 )

 $addr, $maskLength = $cidrNotation -split '/'
 [int]$maskLen = 0
 if (-not [int32]::TryParse($maskLength, [ref] $maskLen)) {
     throw "Cannot parse CIDR mask length string: '$maskLen'"
 }
 if (0 -gt $maskLen -or $maskLen -gt 32) {
     throw "CIDR mask length must be between 0 and 32"
 }
 $ipAddr = [Net.IPAddress]::Parse($addr)
 if ($ipAddr -eq $null) {
     throw "Cannot parse IP address: $addr"
 }
 if ($ipAddr.AddressFamily -ne [Net.Sockets.AddressFamily]::InterNetwork) {
     throw "Can only process CIDR for IPv4"
 }

 $shiftCnt = 32 - $maskLen
 $mask = -bnot ((1 -shl $shiftCnt) - 1)
 $ipNum = [Net.IPAddress]::NetworkToHostOrder([BitConverter]::ToInt32($ipAddr.GetAddressBytes(), 0))
 $ipStart = ($ipNum -band $mask)
 $ipEnd = ($ipNum -bor (-bnot $mask))

 # return as tuple of strings:
 ([BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($ipStart)) | ForEach-Object { $_ } ) -join '.'
 ([BitConverter]::GetBytes([Net.IPAddress]::HostToNetworkOrder($ipEnd)) | ForEach-Object { $_ } ) -join '.'
}

main

This has worked very good for me the last couple of months, thank you Roemer!
I usually lose internet in WSL (using VPN) after sleep mode or moving from Wifi to LAN.

I have adjusted your script to be required to be ran as admin

#Requires -RunAsAdministrator

and to auto delete the routes it finds.

function main {

    $adapterVpn = Get-NetAdapter -InterfaceDescription "<your adapter identifer>"
    $adapterWsl = Get-NetAdapter -Name "vEthernet (WSL)"
    $ipInfoVpn = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapterVpn.ifIndex
    $ipInfoWsl = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $adapterWsl.ifIndex
    $wslCidr = "$($ipInfoWsl.IPAddress)/$($ipInfoWsl.PrefixLength)"

    $ipInfoWslVm = wsl -- ip -o -4 -json addr list eth0 `
        | ConvertFrom-Json `
        | %{ $_.addr_info.local } `
        | ?{ $_ }

    Write-Host "=== VPN (ID $($adapterVpn.ifIndex)) ==="
    Write-Host "IP: $($ipInfoVpn.IPAddress)"
    Write-Host
    Write-Host "=== WSL Adapter (ID $($adapterWsl.ifIndex)) ==="
    Write-Host "IP: $($ipInfoWsl.IPAddress)"
    Write-Host "MASK: $(convert-cidr-to-string -cidr $ipInfoWsl.PrefixLength) (/$($ipInfoWsl.PrefixLength))"
    Write-Host
    Write-Host "=== WSL VM ==="
    Write-Host "IP: $($ipInfoWslVm)"
    Write-Host

    $routesWsl = Get-NetRoute -AddressFamily IPv4 -InterfaceIndex $adapterWsl.ifIndex
    $routesVpn = Get-NetRoute -AddressFamily IPv4 -InterfaceIndex $adapterVpn.ifIndex

    Write-Host "=== Routes for the WSL Adapter ==="
    $routesWsl | Format-Table `
        @{L=Dst Address;E={convert-cidr-range-to-address-string $_.DestinationPrefix}}, `
        @{L=Dst Mask;E={convert-cidr-range-to-mask-string $_.DestinationPrefix}}, `
        @{L="Metric";E={$_.InterfaceMetric + $_.RouteMetric}}, `
        NextHop

    Write-Host "=== Routes for the VPN Adapter ==="
    $routesVpn | Where-Object { is-cidr-in-cidr-range $wslCidr $_.DestinationPrefix } | Format-Table `
        @{L=Dst Address;E={convert-cidr-range-to-address-string $_.DestinationPrefix}}, `
        @{L=Dst Mask;E={convert-cidr-range-to-mask-string $_.DestinationPrefix}}, `
        @{L="Metric";E={$_.InterfaceMetric + $_.RouteMetric}}, `
        NextHop

+    $toDelete = $routesVpn | Where-Object { is-cidr-in-cidr-range $wslCidr $_.DestinationPrefix } 
+    Write-Host "Routes to be deleted:"
+    Write-Host $toDelete
+    Remove-NetRoute -InputObject $toDelete -Confirm:$false
}

@ElvisWai
Copy link

ElvisWai commented Aug 26, 2024

#11002
Modification of Registry Keys
Location: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters
位置: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip6\Parameters
Name: DisabledComponents 名称:DisabledComponents
Type: REG_DWORD 类型: REG_DWORD
Min Value: 0x00 (default value)
Max Value: 0xFF (IPv6 disabled)

change the value to 0x20 (hex) or 32 (decimal) to re-enable IPv6

@dag03tsc
Copy link

dag03tsc commented Oct 11, 2024

In case anyone finds it useful, I've had no single issue over several months, and pretty reliable, robust and fast connections while using the following %HOMEPATH%\.wslconfig file:

[wsl2]
networkingMode=mirrored
firewall=true
dnsTunneling=true
autoProxy=true

[experimental]
hostAddressLoopback=true
autoMemoryReclaim=gradual
sparseVhd=true

Please, kindly check this doc for a description of each property's behaviour, and other properties or values you may find required for your custom setup.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests