microsoft / WSL

Issues found on WSL

Home Page:https://docs.microsoft.com/windows/wsl

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

WSL2 Set static ip?

scrossan-crown opened this issue · comments

This maybe the wrong place to post this but not sure where else to post. Is it currently possible to set a static ip for the WSL2 machine?

I'm loving WSL2 so far with docker and vscode and my only issue is dynamic ip at the moment.

There is a work around. You can port forward to host ip.
Check the below link.
#4150

I agree with the author of the question, please, Wsl2 must have option "static IP". Maybe cmd: wsl --ip <Distro> <IP address>?

My issue isn't just with port forwarding and docker. The biggest issue was that I am using VSCode remote development extension and remote developing in WSL and if I need to restart WSL2 to release some resources then I can't just reconnect in the usual way and any unsaved changes get lost which accidentally happened last week.

@alekseymvt
You could execute any command using wsl like this

wsl -- ifconfig eth0

Any solution?
also see MicrosoftDocs/WSL#418 (comment)

The Hyper-V Switch IP change everytime when the windows reboot, so the gateway in wsl 2 also need to change

Looking for a solution too :)

With the latest update, you can access remote ports(WSL2) as local on Windows Host

You can have a look at this Windows Service - assign a static hostname for WSL machine

With the latest update, you can access remote ports(WSL2) as local on Windows Host

Can anybody check?:
Will "http://mysite" work too, if I add "127.0.0.1 mysite" in "windows/hosts"? or localhost only?

Yes, it should work

It would be nice but instead of WSL 2 ports being bound to 127.0.0.1 they are bound to ::1 and that doesn't work in the browser or hosts file. So we got localhost support but not in a way we can map other domains to it.

@MiklerGM

Yes, it should work

It doesn't, unfortunately. To point a custom domain to WSL, I'm adding a line like 172.25.203.130 mysite.com, where 172.25.203.130 is the IP of eth0 interface of the WSL VM: ip addr show eth0 | grep 'inet\b' | awk '{print $2}' | cut -d/ -f1

@moigagoo check out this https://github.com/shayne/go-wsl2-host you can do it automatically with this service

@MiklerGM Thanks, I've seen it. I'm OK with my own self-written script.

btw, I have no problem accessing the custom domain, for example, test.com from my browser
My hosts file on Windows host machine

127.0.0.1 localhost api db test.com
172.20.124.104 wsl.local

image

@MiklerGM Huh, that's interesting. Tried that several times, it never worked, adn still doesn't 🤔

It works even if you remove the last line, doesn't it? Maybe, you did something else apart from editing hosts file, like installed something like dnsmasq? Also, maybe this Go service does more than just writes to hosts?

@yanyan33333 I'm already on build 18945 but still no joy

image

With the latest update, you can access remote ports(WSL2) as local on Windows Host

Can anybody check?:
Will "http://mysite" work too, if I add "127.0.0.1 mysite" in "windows/hosts"? or localhost only?

Yes, it should work

I confirm it doesn't work.
I would add my custom domain with 127.0.0.1 but doesn't work when I try to access with this domain.
localhost work, but not custom hosts

One work around I've found is if you are using docker and you install the latest edge version. It has support for WSL2 and it uses some magic (not sure what it's doing) but now 127.0.0.1 is working for in my hosts file for the apps in my docker containers on WSL2.

@scrossan-crown it works ,I start nginx on wsl and I can visit the website in windows brower by using localhost

@yanyan33333 I can do the same but can't use 127.0.0.1 in my hosts file with a domain name and access my docker container running on port 80 but I can now that I'm using docker desktop edge version

@yanyan33333

I start nginx on wsl and I can visit the website in windows brower by using localhost

Check custom domain:
WSL2
/etc/nginx/conf.d/mysite.conf ->

server {
    server_name mysite;
    listen 80;
    ...
}

Windows
hosts -> 127.0.0.1 mysite -> http://mysite

@alekseymvt it is working for me
image

I do not have dnsmasq, but I've got service in Go (I should've removed it by now), and a started systemd service. /etc/hosts on my WSL and windows systems are in sync, I did not change anything on WSL.

From my knowledge, this should not affect the GET requests. You can even send GET request via telnet. The domain in your browser's address bar only represents the HTTP Header for HOST directive.

Steps to debug

  • Check that nginx is working correctly on WSL (with all your domains and server_names)
  • Check if windows resolve your hosts correctly.
  • Check windows build number >18945.1001
  • Send the GET request to nginx

In case it is not working

  • Check that nothing is listening to 80 port on your host system or change the nginx port

@MiklerGM

it is working for me

Thank you, I saw your answer. I answered to @yanyan33333, because he wrote about localhost.
I will check a custom domain later for myself, I need download 3Gb :)

We also had a bug where you needed to bind your Linux applications to 0.0.0.0 instead of 127.0.0.1 to access it, which we've fixed. This is being tracked in issue #4353

On build 18963 I can access http://localhost fine but in my Windows host file I have defined domains:
127.0.0.1 www.tripal.john
127.0.0.1 www.tripal3.john
127.0.0.1 clean.tripal3.john
These refuse to connect. Even added them to /etc/hosts. No joy

Set 127.0.0.1 domain in Windows hosts file does not work all the time,even only do nothing.
File I/O in /mnt is slow, so I put my project files in ~/, then IDE should use them by sftp. But when sftp connect for a while, all connections by hosts file will fail.
I use script change hosts file ip to wsl ip, and let project files in /mnt, it works well.
Static IP may be better.

Rider that really what is needed is a static MAC address, on which a static IP can follow as a side effect if desired. Ref #4454, use case being that some software uses the MAC address to implement intellectual property control.

Really the IP address is neither here nor there; the address needs a stable name. Depending on some memorized IP addresses goes against best practice. Acknowledging that this is what a lot of people do, and it is a valid ask. Noting the strategy doesn't work so good with ipv6.

Someone was looking at a $WSL_HOST_IP approach in July ref #4212 (message) although the repo appears empty now.

You can get the WSL2 instance IP address easy enough:

C:>wsl.exe -d Ubuntu-18.04 /bin/bash -c "hostname -I | awk '{print $1}'"
172.21.141.235

And the other direction:

$ ip route | grep default | awk '{print $3}'
172.21.128.1

Those can be assigned to environment variables to taste. But that's not really the ask(s).

Changing the guest VM static IP address here doesn't satisfy the behavior that the WSL-side bridge /16 will change on every subsequent reboot. The problem needs to be resolved on both Host side and Guest side, and we cannot control Host.

You can be deterministic about the IP address you get within 172.21.0.0/16 -- but we cannot even be sure you are in 172.21.0.0/16 in the first place.

An additional use case is to enable easily remote debugging with Linux hosted servers and W10 hosted IDE.
concrete example is PHP-fpm server with XDebug Zend extension on WSL2 (node should be the same headache, python is OK because remote debugging is on SSH)
trying to connect XDebug agent inside VS Code (PHP Debug extension)

As of now, the setup is complex:

VS Code must listen on hostname 0.0.0.0 (and not the default localhost)
PHP-fpm must be setup with remote host on IP of host (nameserver inside /etc/resolv.conf
(the xdebug.remote_host must be setup on Windows IP to dialog with VS Code) - if not , the Xdebug will never be able to go outside WSL2 boxing to the Windows hosted listening agent.

moreover, Windows firewall / defender must authorise VS Code to listen on Private

=> a Static IP or an env variable could be clearly make this simpler
my 2 cents

I haven't used PHP-fpm, but at least with my plugin of choice (cpptools) remote development works (to a first order) out of the box with WSL Remote and/or SSH Remote. Is this not the case with PHP? If not I'll burn some cycles and take a look to better grok what you are describing.

must be setup with remote host on IP of host

You don't need an IP address. This is what I have been trying to drive at. Whatever you are setting up configuration-wise surely is able to take a name. Having to choose and setup a static IP somewhere for WSL, and then configure that same static IP somewhere else like your PHP environment configuration thingy (probably lots of somewhere else-else too) is at least one configuration step too many. That configuration field could instead have hostname wslhost or wslhost.local (or bikeshed your naming preference) and you'd be done.

Someone (at least with their inside voice) is going to say "yeah but once localhost sharing is available in both directions, you'll just use localhost". Which is not wrong, up to a point; but everything that wants to use a popular port on both Windows and WSL, glaringly SSH port 22, makes for an unnecessary configuration headache with having configure and use port 2222 on one side or t'other.

[Worse, SMB port 445 can't be shared on localhost period, because Windows (inexplicably) hogs 445 on 0.0.0.0 with no way I've found to netmask it. Likewise you can't choose a nonstandard port to serve SMB on the WSL side (say 4445) because there is no way on the Windows side to net use with a nonstandard port or convince Explorer to take a smb://hostname:port/path URI. Caveat "that I know of".]

TL;DR This all is solved if a hostname for the WSL IP is available on the Windows side -- whatever that IP address turns out to be, static or otherwise.

+1 for the need of out-of-the-box hostnames for IP addresses generated inside /etc/hosts with legacy hosts file as an additional option of /etc/wsl.conf
Could you propose a standard ?
wsl.host wsl.host.local could be the IP to the windows host ( found in /etc/resolv.conf)
wsl.debian
wsl.ubuntu …. wsl.<distriName> could be the IP for each distribution.(found with ip addr )
At the glance:

-------------------------------------------
|    Win10 : The **WSL Host**             |
|     for several distributions           |
|                                         |
|       wsl.distributionName              |
|        |                                |
|     ---v-----------------               |
|    | WSL distribution1 | ---> wsl.host  |
|     ---------------------               |
|                                         |
-------------------------------------------

PHP specific:
PHP's XDebug protocol: DBGP is not SSH out of the box.
The server's agent has to connect to the IDE's XDebug listening port. (wsl.host:9000)
and this must be setup in the php.ini

+1:
Remote WSL is really a must-have for editing PHP files directly inside the WSL

/etc/hosts with legacy hosts file

Not (just) /etc/hosts. It would be C:\Windows\System32\Drivers\etc\hosts too. That's assuming the Windows-proper people were amenable to WSL banging on their hosts file.

But I think (?) it can be done all in the container itself with mDNS. I even took a very half-hearted run at it for a few hours in July, but never made the necessary effort to prove the premise.

wsl.<distriName>

Or maybe (f.e.) DESKTOP-BNN97ME.wsl.debian.local or just DESKTOP-BNN97ME.debian.local or DESKTOP-BNN97ME.debian, where DESKTOP-BNN97ME is my Windows hostname. That's if we want to make WSL container visible on the rest of the local segment, firewall rules notwithstanding. The general idea would require some more thought and effort.

commented

I tried to use a command to set both /etc/hosts and C:/Windows/System32/drivers/etc/hosts

It works for /etc/hosts, but I don't have permission to set C:\Windows\System32\Drivers\etc\hosts
(I can use vim to change the file content without sudo, but can not use sed)

I have tried sudo for Windows but it will cause UAC warning.

Any idea to change the C:/Windows/System32/drivers/etc/hosts without UAC warning?


#!/bin/sh
export HOSTIP=$(cat /etc/resolv.conf | grep 'nameserver' | cut -f 2 -d ' ')
export CLIENTIP=$(ip addr show eth0 | grep 'inet ' | cut -f 6 -d ' ' | cut -f 1 -d '/')
echo $HOSTIP
echo $CLIENTIP
echo "<your password>" | sudo -S sed -i "/winhost/c $HOSTIP\twinhost" /etc/hosts 

(Before runing this, add a line with winhost first)

Any idea to change the C:/Windows/System32/drivers/etc/hosts without UAC warning?

Without a UAC? Doable but not straightforward, because you're giving a non-privileged user escalation rights to that file.

One way to do it would be a schmancy LocalSystem account service on the Windows side; communicate with that using a RPC mechanism of choice.

[Not strictly related but along the same lines, I wrote a small daemon to proxy pcap here which needs to run as Administrator to work. I never actually made the effort to turn it into a Windows Service, but that step would amount to turning the main() there into service startup entry point. It uses TCP as the transport and rpclib.]

commented

@therealkenc

Thanks.

I have add the permission of C:/Windows/System32/drivers/etc/hosts to my Windows login account.

And now, I can use vim Ex mode to modify the hosts file.


Maybe somebody need this.

#!/bin/sh
export WINIP=$(cat /etc/resolv.conf | grep 'nameserver' | cut -f 2 -d ' ') 
export WSLIP=$(ip addr show eth0 | grep 'inet ' | cut -f 6 -d ' ' | cut -f 1 -d '/')
echo $WINIP
echo $WSLIP
echo "<Password>" | sudo -S sed -i "/winip/c $WINIP\twinip" /etc/hosts
echo "%s/^.*wslip/$WSLIP\t\twslip/g|wq" | vim -E /mnt/c/Windows/System32/drivers/etc/hosts

Yeah; I didn't want to even mention that as an option. Now any program that runs as user you can, without any special rights or trouble, spoof any address (for example, your bank's). Maybe that doesn't matter in your specific workflow. But anyone looking to replicating the approach should be aware of that.

commented

Looks like if WSL2 can boot up with a static IP, it will solve all those kind of issue.... I also found WSL2 is conflict with my VPN when it's getting an ip address of 172.x.x.x.
Current I am still using WSL1. I will change to WSL2 if some day it can support static IP.

PLEASE note: The shell script is wrong and is not waiting for input in the moment when password is required. Apart from that please also read carefully therealkenc's comment #4210 (comment) regarding security.

I do not even know what this wants to do: echo "%s/^.*wslip/$WSLIP\t\twslip/g|wq" | vim -E ? The echo will not work here the way you expect, @OhYee .

And BTW, what about this message in /etc/hosts then? It seems to be autogenerated and will override the mentioned modifications:

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

commented

Here's a couple methods I've used to reference the Windows host address from WSL...

Install libnss-myhostname, a plugin for the Name Service Switch. It will always assign a hostname of _gateway that resolves to the current gateway/default route addresses, ordered by their metric. I use it for my X-server DISPLAY variable and it always resolves to the Windows host address, regardless of the current network configuration.

Also, since the Windows host and WSL have the same hostname, you can append a . (dot) to the hostname, which is how you request the hostname for the host closest to the root zone. The name server is running in Windows, so naturally its hostname is closer to the root zone. Windows also adds a $NAME variable to the shell environment when launching WSL, and it's value is the system hostname. So, the Windows host can be reached at ${NAME}. (notice the dot suffix, indicating we want the host closest to the root zone)

@xtremeperf which X server do you use?

Loving WSL 2 from the first day.
Yet the random IP is really an issue which sometimes confilicts with my company VPN subnet and I have to reboot the host to walk around.

Yes, WSL2 is awesome, I'm back under Windows after 15 years of OS X use. The only annoying thing I found for the moment is the dynamic IP of WSL2 VM. I hope it'll be available soon.

commented

@craigloewen-msft && @benhillis && @therealkenc

Can we get any updates on any of these issues regarding static IPs and/or usage of DefaultSwitch? Thanks!

I need to join the WSL2 instance to an AD domain. Correct me if I'm wrong, but as far as I can tell this would require greater control over the WSL2 network interface and IP configuration than we currently have, won't it?

What are we trying to solve ? Dynamic IP addresses.
Why not use similar idea like DynDNS services?

Here is what I am thinking:

  1. WSL boots up
  2. From within WSL, add a script at the end of the init process to:
    1. Figure out its own IP address
    2. Tell the host system

For that last point, there are multiple options:

  • using the gateway IP, send the new dynamic IP to a process on the host
  • directly call an .exe on the host to update the IP address (my preferred option)

I'm not a huge fan of the whole service idea, but having an extra init script in WSL itself could resolve the problem with most flexibility, and with least side effects.

What are we trying to solve ? Dynamic IP addresses.
Why not use similar idea like DynDNS services?

Here is what I am thinking:

  1. WSL boots up

  2. From within WSL, add a script at the end of the init process to:

    1. Figure out its own IP address
    2. Tell the host system

For that last point, there are multiple options:

  • using the gateway IP, send the new dynamic IP to a process on the host
  • directly call an .exe on the host to update the IP address (my preferred option)

I'm not a huge fan of the whole service idea, but having an extra init script in WSL itself could resolve the problem with most flexibility, and with least side effects.

I mod the #4150 (comment) script to update my hosts:
https://github.com/lengthmin/dotfiles/blob/master/windows/wsl2.ps1
save as wsl2.ps1 on your computer.

the line2 and line3 is the domain you wanted.
and create an task scheduler on Hyper-V create a WSL switch.

How To:

  1. Launch Event Viewer
    Hit Start, type “Event Viewer” into the search box, and then click the result.
    You can refer to this: http://techgenix.com/attaching-tasks-event-viewer-logs-events/

  2. Select System
    in the left panel, select Windows Logs -> System

  3. find events which source is Hyper-V-VmSwith

  4. find the event which is "create switch"
    click each entry of step 3, find the message is : Port xxxxx successfully created on switch xxxx (Friendly Name: WSL)

  5. right click the entry and then click the "Attach Task To This Event..."

  6. click next, in the action tab, select Start a program, input the program: powershell, the argument is the wsl2.ps1, and select next, finish.

  7. Go to search, search for task scheduler. Select the Event Viewer Tasks, and right click your task just created, select properties, In the "General" tab, Select "Run with highest privileges".
    You can refer to this: https://superuser.com/questions/770420/schedule-a-task-with-admin-privileges-without-a-user-prompt-in-windows-7

Does somebody know how many topics are about this issue? And are you going to give a solution?

That's the big difference with OpenSource, i'd resolve this in 5min.

so frustrating.. the localhost still doesn't work all the time

i don't know it is a right solution for everyone, but believe me i could solve this problem in a very weird way which is not compatible for everyone
the way i solved this problem made the cost.
i bought an extra wireless adapter for my pc and now my pc is making connection from two adapters
one is connecting through the LAN connection
and the second one is connected from wireless adapter
so if i check my device manager, i have two adapter installed in my machine
so as @#4150 (comment) said we need to change WSL adapter from internal to external
but in previous days i couldn't make connection both in my windows and Linux altogether
but now i have two adapters which i can assign one adapter to WSL and another one can be used for my windows connection

after assigning your adapter to your WSL machine from Hyper-V manager, you just need to change wsl ip to the ip of your connection
just write

sudo ifconfig eth0 <your_ip> netmask 255.255.255.0 up
sudo route add default gw 192.168.xxx eth0
then remove resolv.conf file and make wsl.conf file
and in wsl file write down
[network]
generateResolvConf = false

and after that, you should create resolv.conf once again, put your DNS inside this file
like example below:

nameserver 8.8.8.8
nameserver 8.8.4.4

don't forget that each time you shutdown your machine or either your Linux, you have to assign ip once again because this method is not permanent (if you know the permanent way, i am happy to hear)

now I can ssh to another machine in local area
i know this is not a great solution for everyone, but it's working like a charm for me

please Microsoft think more about this issue

commented

@illustrayking you could work around the non-permanent issue by making a startup script in WSL that changes the needed settings / files. It is still not a pretty solution... it's literally workaround upon workaround. New add-in card or USB adapter is the least of my worries, my desktop PC already has 2 LAN ports on it's motherboard.. but even though I like tinkering, and could make this work, it's actually MORE work than - simply installing Linux in a Hyper-V VM.

So; not sure if this is around just accessing it from localhost; maybe I need to make this comment elsewhere but I did notice that if docker desktop is installed and the WSL2 integration is turned on; that setting items such as these:

127.0.0.1 mysite.com

Do not work until you run wsl --shutdown and open a terminal tab again.

I haven't tested yet if it's docker related or the startup order, but simply restarting the WSL container after logging into my machine when everything else has started fixes issues access from 127.0.0.1, localhost and custom domains.

I have my docker setup in windows to be integrated with WSL2 (latest slow ring) so that I don't need to install it inside the WSL2 image. Previously I had docker in the image and had to start it manually each boot.

Okay, my issue was that "Fast Startup" was turned on; so it was not regenerating the host mapping correctly and used the previous IP address on startup.

Opened up power options in control panel > choose what to do when power buttons are pressed > show unavailable options > uncheck fast startup.

Done and fixed for me.

i don't know it is a right solution for everyone, but believe me i could solve this problem in a very weird way which is not compatible for everyone
the way i solved this problem made the cost.
i bought an extra wireless adapter for my pc and now my pc is making connection from two adapters
one is connecting through the LAN connection
and the second one is connected from wireless adapter
so if i check my device manager, i have two adapter installed in my machine
so as @#4150 (comment) said we need to change WSL adapter from internal to external
but in previous days i couldn't make connection both in my windows and Linux altogether
but now i have two adapters which i can assign one adapter to WSL and another one can be used for my windows connection

after assigning your adapter to your WSL machine from Hyper-V manager, you just need to change wsl ip to the ip of your connection
just write

sudo ifconfig eth0 <your_ip> netmask 255.255.255.0 up
sudo route add default gw 192.168.xxx eth0
then remove resolv.conf file and make wsl.conf file
and in wsl file write down
[network]
generateResolvConf = false

and after that, you should create resolv.conf once again, put your DNS inside this file
like example below:

nameserver 8.8.8.8
nameserver 8.8.4.4

don't forget that each time you shutdown your machine or either your Linux, you have to assign ip once again because this method is not permanent (if you know the permanent way, i am happy to hear)

now I can ssh to another machine in local area
i know this is not a great solution for everyone, but it's working like a charm for me

please Microsoft think more about this issue

You can also just bridge vEthernet (WSL) and your primary network interface. After that process is same as you explained.
I tested this on windows host running in wmvare, but it should be same for a non virtual host.

<PCNAME>.mshome.net always resolves to the IP address of the host machine from both host and wsl side.

Pinging GW-DESKTOP.mshome.net [172.24.224.1] with 32 bytes of data:
Reply from 172.24.224.1: bytes=32 time<1ms TTL=128
PING GW-DESKTOP.mshome.net (172.24.224.1) 56(84) bytes of data.
64 bytes from GW-DESKTOP.mshome.net (172.24.224.1): icmp_seq=1 ttl=128 time=0.268 ms

My apologies. Has worked 100% for me sofar. Not sure whats going on.

On my ubuntu install

sudo apt-get install -y avahi-daemon
sudo /etc/init.d/dbus start
sudo /etc/init.d/avahi-daemon start

Then <PCNAME>.local resolves to your windows machine
and <PCNAME>-2.local resolves to your ubuntu machine

You can also override the published hostname of your linux machine in /etc/avahi/avahi-daemon.conf for example

[server]
host-name=WSL

so WSL.local will now resolve to your wsl machine.

And this will apply to any lookups run on any mDNS enabled machines on your local LAN.

You can access any port on WSL2 using the 127.0.1.1 IP
127.0.0.1 points to host and 127.0.1.1 to WSL.

Works well with ubuntu and docker :)

You can access any port on WSL2 using the 127.0.1.1 IP
127.0.0.1 points to host and 127.0.1.1 to WSL.

Works well with ubuntu and docker :)

This doesn't seem to be the case for me. Using the full external IP works fine, but when I change it to 127.0.1.1, it just doesn't work at all. Ubuntu 18.04.4 LTS, WSL 2, Windows 19041.208.

I don't know why Microsoft makes this simple question be sooooooo complete.
Why wsl2 have dynamic IP? Because wsl2 uses the stupid 'Default Hyper-V Switch' . This Switch will be deleted and recreated after reboot.

To solve this problem, just give us a way to change wsl2's switch from 'Default Hyper-V Switch' to other custom Hyper-V Switch that has static network segmentcustom .

It will simplely solve this problem.

All the methods above(dynamic hosts, port forward etc...) are OK. But they can't solve the fundamental problem: Because wsl2 has no static IP, any computer on LAN can't connect to wsl2's port or files.

For example, there is a Windows 10 virtual machine on my computer, I want to share wsl2's files to the Windows 10 virturl machine(or other computer on LAN) by samba. Is there a way to do it? No, there is no way to do it.
Because wsl2's ip is random. Just give us a static IP can solve this problem.

1 year has passed, Microsoft still does not want to solve this problem
Maybe Microsoft thinks if wsl2 has a static IP, a lot of web service will run on wsl2 (nginx, apache etc..) instead of IIS?

I don't know why Microsoft makes this simple question be sooooooo complete.
Why wsl2 have dynamic IP? Because wsl2 uses the stupid 'Default Hyper-V Switch' . This Switch will be deleted and recreated after reboot.

To solve this problem, just give us a way to change wsl2's switch from 'Default Hyper-V Switch' to other custom Hyper-V Switch that has static network segmentcustom .

It will simplely solve this problem.

All the methods above(dynamic hosts, port forward etc...) are OK. But they can't solve the fundamental problem: Because wsl2 has no static IP, any computer on LAN can't connect to wsl2's port or files.

For example, there is a Windows 10 virtual machine on my computer, I want to share wsl2's files to the Windows 10 virturl machine(or other computer on LAN) by samba. Is there a way to do it? No, there is no way to do it.
Because wsl2's ip is random. Just give us a static IP can solve this problem.

1 year has passed, Microsoft still does not want to solve this problem
Maybe Microsoft thinks if wsl2 has a static IP, a lot of web service will run on wsl2 (nginx, apache etc..) instead of IIS?

@ueinohakono #4150 (comment)

You can access any port on WSL2 using the 127.0.1.1 IP
127.0.0.1 points to host and 127.0.1.1 to WSL.
Works well with ubuntu and docker :)

This doesn't seem to be the case for me. Using the full external IP works fine, but when I change it to 127.0.1.1, it just doesn't work at all. Ubuntu 18.04.4 LTS, WSL 2, Windows 19041.208.

It doesn't work for me all the time either. It works only for some applications, while the others don't. So frustrating...
Build 19577 200228-1439

wsl -- ifconfig eth0

@alekseymvt
You could execute any command using wsl like this

wsl -- ifconfig eth0

Thank´s, it is worked for me

I wrote powershell script to automate WSL IP's changing in Windows hosts file: WSLSync

Currently i'ts in Beta stage but I think it's close to completion. Feel free to test, contribute if anyone want to :)

commented

There is a work around. You can port forward to host ip.
Check the below link.
#4150

Since a normal hyper-v host can set up a virtual switch to customize the network, Microsoft should also provide a tool to set up WSL instead of letting users write scripts themselves.

Scribbling your Windows hosts file elevated is not particularly recomended (but free country, natch). The suggestion by gwharton to start up avahi-daemon(8) is sound (thanks Grahm). It also has the amiable property of being both the correct and standard solution to the problem of LAN IPs that come and go (like ours). [n.b. You'll get better eyeballs on configuring avahi in a forum dedicated to that sort of thing rather than in this WSL github issue.]

I wrote powershell script to automate WSL IP's changing in Windows hosts file: WSLSync

Currently i'ts in Beta stage but I think it's close to completion. Feel free to test, contribute if anyone want to :)

Cool! I created something the same but more simplier: https://gist.github.com/MichaelBelgium/2243e5713833ba44b5675d844eeb1c85

I wrote powershell script to automate WSL IP's changing in Windows hosts file: WSLSync
Currently i'ts in Beta stage but I think it's close to completion. Feel free to test, contribute if anyone want to :)

Cool! I created something the same but more simplier: https://gist.github.com/MichaelBelgium/2243e5713833ba44b5675d844eeb1c85

Loving it. thanks dude

Cool! I created something the same but more simplier: https://gist.github.com/MichaelBelgium/2243e5713833ba44b5675d844eeb1c85

It is a nice work around! However it would be better if there would be either a fixed host name or a fixed ip address to ease development on a windows and wsl2 system simultaneously.

commented

Any update about having a static IP?

Any update about having a static IP?

The situation remains dynamic.

I was looking forward to WSL2, but I held back on updating to 2004 for various reasons until last weekend.
I then updated my main environment to WSL2 and it broke my rsync backups, because now I can't easily ssh in from outside. I can't switch the WSL switch to bridged mode, as I already have a bridge for Hyper-V and only one network interface.

Clearly, the solution here is telling WSL, on a per-instance basis, which switch to use and let the VM manage its network, so why a year into development we don't have that?

switching back to a HyperV VM which has a fix ip and more.

HyperV changes ip every restart too, WSL 2 and HyperV are using the same adapter afaik

@MichaelBelgium depends on how you set it up. I have mine set up in bridged mode and VM manages its virtual NIC like any normal Linux box would.

I give you a new idea: Instead of changing the IP, add a designated IP.

In Windows 10, run CMD or Powershell with administrator privilege, and then execute the following two commands:

:: Add an IP address in Ubuntu, 192.168.50.16, named eth0:1
wsl -d Ubuntu -u root ip addr add 192.168.50.16/24 broadcast 192.168.50.255 dev eth0 label eth0:1

:: Add an IP address in Win10, 192.168.50.88
netsh interface ip add address "vEthernet (WSL)" 192.168.50.88 255.255.255.0

In the future, you will use 192.168.50.16 when you access Ubuntu, and 192.168.50.88 when you access Win10.
You can save the above two lines of commands as a .bat file, and then put it into the boot area, and let it execute automatically every time.

Except this does nothing in cases where you need to have SSH connections to WSL from other device in LAN (which worked perfectly fine in WSL1).
The solution here would be to allow selecting a bridged interface and let the VM handle its own network configuration.

It's absurd to me this isn't fixed yet after a year. I mean, I find it inconceivable hyper-v itself wouldn't have the functionality of being able to specify the ip address of a virtual network interface to be created, so the issue must simply exist in how wsl2 implements this. Can't a person on the wsl team just ask the hyper-v team how to proceed here? Seems like a major failing of internal communication here to have this issue remain for a year

commented

Yes, it should work

Does not work for me. curl localhost:<port> works but curl local.custom.com:<port> does not

On my computer I needed to windows from scratch. I discovered that on the most recent windows 10 version the problems with wsl2 are fixed; I'm now able to access a webserver (running from wsl2) from my browser via localhost.

I'm on Windows 2004 and still have this issue.
PS: occurs after waking from sleep.

More than a year reported issue and still no progress? Really?

Please get this sorted Mr. Microsoft, we want true integration, and we want it now! Please :-)

@litecart-cs @DTCM86 You can actually set up the static ip address inside wsl. I used netplan to set up the static ip address(assuming your os is ubuntu). But some servers became unreachable after the setup. I'm still trying to figure out what's really going on. Maybe it's not a good idea to change it. Anyway, here's how to set static ip address. https://linuxize.com/post/how-to-configure-static-ip-address-on-ubuntu-20-04/

@AlexLu202 I believe the issue lies with vSwitch used by WSL2, you'd need to connect it to a different network interface as well.
Honestly, at this point I'd rather go with a full Hyper-V guest and expose a network share, that I could then use as a working environment.
If anyone is interested, @ me and I'll see if I can come up with some simple instructions or maybe even an Ansible role.

I give you a new idea: Instead of changing the IP, add a designated IP.

In Windows 10, run CMD or Powershell with administrator privilege, and then execute the following two commands:

:: Add an IP address in Ubuntu, 192.168.50.16, named eth0:1
wsl -d Ubuntu -u root ip addr add 192.168.50.16/24 broadcast 192.168.50.255 dev eth0 label eth0:1

:: Add an IP address in Win10, 192.168.50.88
netsh interface ip add address "vEthernet (WSL)" 192.168.50.88 255.255.255.0

In the future, you will use 192.168.50.16 when you access Ubuntu, and 192.168.50.88 when you access Win10.
You can save the above two lines of commands as a .bat file, and then put it into the boot area, and let it execute automatically every time.

To be able to access from another device on the LAN I had to add another line to the batch file:

netsh interface portproxy add v4tov4 listenport=22 listenaddress=0.0.0.0 connectport=22 connectaddress=192.168.50.16

windows can use wsl2's service by localhost:port, but wsl2 can't use windows's service. so we can change the dynamic ip to a domain:

echo `cat /etc/resolv.conf|grep nameserver|awk '{print $2}'` win10.local >> /etc/hosts

then we can use win10.local as a static domain.

@transtone please, stop with irrelevant workarounds.

We need a fix, for an issue that is over a year old.

@transtone please, stop with irrelevant workarounds.

We need a fix, for an issue that is over a year old.

Before it been fixed, may some one like me want to find a temporary workarounds?
It may irrelevant you, so you can just fix it and close this issue.

HyperV, virtual switch shared with pc, full Ubuntu, static networking, vscode with remote SSH module. Flush wsl down the crapper. Now stop your whining!!!!! Out.

commented

I was able to define a static IP address in WSL 2 VM like this on Windows 10 Home:

  1. enable systemd in your WSL 2: https://github.com/DamionGans/ubuntu-wsl2-systemd-script

  2. bridge the vEthernet (WSL) and your ethernet Local Area Connection in Windows' Network Connections

  3. /etc/resolv.conf is linked to ../run/resolvconf/resolv.conf but resolvconf was not installed. To fix:

cat > /etc/wsl.conf <<EOF
[network]
generateResolvConf = false
EOF
  1. use systemd-networkd to configure a static IP address in your WSL 2 VM
/etc/systemd/network/lan.network:

[Match]
Name=eth0

[Network]
Description=lan
DHCP=no
Address=192.168.1.20/24
Gateway=192.168.1.1
DNS=192.168.1.1
LLDP=true
EmitLLDP=true

(shutdown the VM on Windows side with wsl --shutdown and start it again)

rm -f /etc/resolv.conf

echo "nameserver 192.168.1.1" > /etc/resolv.conf

To test:

  1. install/configure/enable/start ssh.service in WSL 2 VM
apt-get install openssh-server
dpkg-reconfigure openssh-server # this creates the ssh host keys in /etc/ssh
systemctl enable ssh
systemctl start ssh
  1. connect to port 22 on your WSL 2 VM IP 192.168.1.20

I was able to define a static IP address in WSL 2 VM like this on Windows 10 Home:

1. enable systemd in your WSL 2: https://github.com/DamionGans/ubuntu-wsl2-systemd-script

2. bridge the vEthernet (WSL) and your ethernet Local Area Connection in Windows' Network Connections

3. /etc/resolv.conf is linked to ../run/resolvconf/resolv.conf but resolvconf was not installed. To fix:
cat > /etc/wsl.conf <<EOF
[network]
generateResolvConf = false
EOF
1. use systemd-networkd to configure a static IP address in your WSL 2 VM
/etc/systemd/network/lan.network:

......

Do not do this. It will break your Hyper networking and cause other yet unreasonable problems. While it technically works, but the WSL network adapter is recreated after every reboot, which means you have to first start wsl and then you have to re-bridge the network adapters. I'm not sure if there is a good way to undo these changes so I would strongly not recommend doing this to a WSL which is already setup and you are using.

commented

It will break your Hyper networking and cause other yet unreasonable problems.

What's the problem you experienced using this solution?

It will break your Hyper networking and cause other yet unreasonable problems.

What's the problem you experienced using this solution?

Like I said it breaks hyper-v networking. And in addition, everytime you reboot the machine, you have to manually add the WSL virtual network adapter back to the network bridge. There is no way to script creation of network bridges nor are there reg keys which you can change.

and there is no clear way (that I see at the moment) to remove the changes from the systemd script hack.

This maybe the wrong place to post this but not sure where else to post. Is it currently possible to set a static ip for the WSL2 machine?

I'm loving WSL2 so far with docker and vscode and my only issue is dynamic ip at the moment.

hello, I have the same problem.
I use docker in windows10, and I found that the ip address on vEthernet (WSL) change everytime when I restart windows. It leads to I can't access Windows resources from Linux.
For example, I run an application using docker to access the mySQL running on windows host, I can't connect to mysql-server running on windows when I use the orignal config.
because ip address on the vEthernet (WSL) had changed, but the mysql-host ip in my original config as same as last time.
What can I do to keep the IP address of vEthernet (WSL) unchanged when I restart windows?
thanks~

Add ip address when wsl starts
For example
wsl -d kali-linux -- ifconfig eth0 add 172.31.155.100 netmask 255.255.240.0 broadcast 172.31.159.255

wsl -d kali-linux -- ifconfig eth0 add 172.31.155.100 netmask 255.255.240.0 broadcast 172.31.159.255

...which creates an interface in WSL-managed V-Switch, i.e. useless.

Again, the proper fix would be to allow us to assign the WSL distro to a different V-Switch.

FWIW, I migrated my setup to hyper-v, where admittedly this still isn't that easy to set up, but at least you get it working properly.