Access a localhost running in Windows from inside WSL2? [closed] - windows

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Closed last year.
The community reviewed whether to reopen this question 9 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I am running a local AEM server in my Windows machine. The server is running on localhost:4502. I am using Ubuntu distro running in WSL2 for my development. I want to access the localhost:4502 running in the Windows machine in my WSL2 Ubuntu.
Is there any way to do that or is it not possible ?

Short answer for most recent Windows versions
mDNS has been a feature of WSL2 for a while now. Concatenating your WSL2 hostname (or the equivalent command/function in your programming/language environment) with ".local" should get you access.
For example, from Bash, try:
ping "$(hostname).local"
For instance, if your hostname is "MyComputer", then the mDNS should be MyComputer.local.
If ICMP is blocked (as it seems to be on new Windows 11 installs), or if you want to test the connection to the actual port, then use netcat. It's available by default in the WSL Ubuntu installation, but may need to be installed in other distributions like openSUSE:
nc -zv "$(hostname).local" <portnumber>
Why localhost doesn't work
WSL2 is running with a virtual network (vNIC) that is created by the Windows Virtual Machine Platform (a subset of Hyper-V). Inside WSL2, localhost is the address of the vNIC.
What you need
WSL2 also sets up a virtual router on the Windows host to allow connectivity to both the outside world as well as the Windows host. You can see this via:
ip route
This is the address you need to use for the Windows host.
You could, of course, parse it from the route (or, as in an earlier answer, from /etc/resolv.conf), but WSL sets up a convenience mDNS (the .local domain) using the Windows "computer name", which is also used as the hostname of the WSL instance.
So concatenating $(hostname) (or it's equivalent in your programming/language environment) with ".local" should get you access.
Other considerations:
mDNS is reliant on the Windows host to resolve the name. If you have changed your /etc/resolv.conf under WSL, then this will likely not work.
Remember to open any necessary firewall ports. WSL2 is considered a separate network from that of the Windows host. Windows will consider network connections from WSL2 to be coming from an external source. (Credit to #RamilGilfanov for a comment pointing this out)
The first time a connection is made from WSL2 to a particular port, Windows Defender (if that is your firewall) will typically display a dialog asking if you want to grant access. However, in my experience, this dialog often gets buried under the main window due to timing of mouse-clicks, keyboard, etc., so it's easy to miss.
Remember to have your Windows service accept connections from remote hosts.
Many servers are configured by default to bind to localhost/127.0.0.1. Because WSL2 appears to Windows as a remote network, you'll typically need to update your configuration to bind to 0.0.0.0 or a specific address.
Note that, since the address for WSL2 changes after each reboot, it can be difficult to update your configuration each time. If at all possible, use 0.0.0.0 unless there are security concerns. Since WSL is designed for development rather than production, this shouldn't be an issue.

I was also looking for some solution to do this but currently, there is no such option available. Check out this GitHub issue:
https://github.com/microsoft/WSL/issues/4619
One solution can be this:
If you have the IP of windows(host) then it will do the job but the only problem is that IP will change every time. But, WSL2 stores your windows(host) IP in /etc/resolv.conf file. So we can modify our etc/hosts to map winhost to the IP dynamically.
Add the following lines at the end of ~/.bashrc file. This will grep the IP and modify the etc/hosts when you boot the WSL.
export winhost=$(cat /etc/resolv.conf | grep nameserver | awk '{ print $2 }')
if [ ! -n "$(grep -P "[[:space:]]winhost" /etc/hosts)" ]; then
printf "%s\t%s\n" "$winhost" "winhost" | sudo tee -a "/etc/hosts"
fi
then run the following command to reload the changes.
$ source ~/.bashrc
now you can use winhost instead of localhost in WSL2(client) to access the servers running windows(host). In your case, it will be winhost:4502 but this will work for any other use cases as well like accessing Postgres/MySQL server running on windows, etc.
NOTE: Always remember to configure your firewall on windows to allow those ports so that WSL2 can access otherwise your connection may get blocked by firewall.

You need add ipv6 rule in hosts file.
Like:
127.0.0.1 example.com
::1 example.com localhost
I had a similar problem and found the solution at this link:
https://github.com/microsoft/WSL/issues/5728

This is simple, you just need to do 2 things. set ip address to localhost in hosts file and allow windows firewall to allow incoming connections.
Here are steps by step instructions:
Get IP address, open cmd type ipconfig /all, note down ip address 172.22.16.1
Open notepad as administrator, File->open , browse to C:\Windows\System32\drivers\etc\hosts , add line 172.22.16.1 localhost, save and close.
Last option is to allow Firewall rules to accept public connections, for this open control panel > System and Security > Windows Defender Firewall > Advanced Settings > Inbound Rules > 'New Rule`
Rule Type : choose Port , click next
Protocol and Ports : type *Specific local port: 4502 , click next
Action : Allow the connection , click next
Profile : check Public , click next
Name : type AEM server , click finish
close other windows, again open cmd , type wsl --shutdown for shutdown ubuntu subsystem.
open ubuntu again.
testing connection type curl localhost:4502 in command prompt. if it returns something means you are good to go.

The easy way:
in ubuntu command line type: ip route
default via 172.23.96.1 dev eth0
172.23.96.0/20 dev eth0 proto kernel scope link src 172.23.97.122
In your app, config the host to: 172.23.97.122
Now you can access using Windows Browser

This really belongs on another forum, but I suspect you could do this.
Step 1. Run your AEM server on your actual IP address (or all addresses) instead of binding to just localhost.
Step 2. Your Ubuntu WSL client instance won't share localhost with the host machine, but it will share the local IP address your machine actually has (e.g. 10.0.0.2). Just have your client connect to that IP address instead of localhost.
I don't know anything about AEM, but you might need to secure it if you are exposing it to a larger network. Block port 4502 on the upstream firewall or use a Windows Firewall rule to only allow incoming on port 4502 from your own IP address. This certainly appears possible.

Windows 10 considers localhost as ::1
Ubuntu considers localhost as 127.0.0.1
So solution is to create a mapping
create a file called .wslconfig in C:\Users<your_username>.wslconfig
add the following to it.
[wsl2]
localhostForwarding=true
PS: I dont know if it mess up anything else but it helped me run django servers which were broken after upgrading to wsl2

Related

Localhost refused to connect on WSL2 when accessed via https://localhost:8000/ but works when using internal WSL IP adress

What I'm Trying to Achieve
To access localhost from my local machine during the development of a Symfony web app.
My Environment
WSL2 running on Windows 10
Linux, Apache2, MySQL, PHP-7.4 stack (with Xdebug3 intalled)
Debian 10
Symfony 5.4 (although not sure on if relevant to this problem)
Steps I've Taken
Set up WSL2 according to this Microsoft WSL2 tutorial
Set up LAMP stack according to this Digital Ocean tutorial
Set up Symfony according to this Symfony tutorial
Run the following bash script on startup to start my services and set the host to the virtual WSL IP in my xdebug.ini file
#!/bin/sh
REMOTEIP=`cat /etc/resolv.conf | grep nameserver | sed 's/nameserver\s//'`
sed -i -E "s/client_host=[0-9\.]+/client_host=$REMOTEIP/g" /etc/php/7.4/mods-available/xdebug.ini
service php7.4-fpm start
service apache2 start
service mysql start
Run my Symfony project on the development server using symfony serve -d (Symfony then tells me "The Web server is using PHP FPM 7.4.23 https://127.0.0.1:8000")
Go to https://localhost:8000/ in Chrome where the app is running
What I Expect to Happen
My Symfony web app to be running on https://localhost:8000/ when I visit the URL in my Chrome browser
What Actually Happens
I get "This site can't be reached localhost refused to connect." in the Chrome browser
What I've Tried
This used to happen less frequently and I would give my laptop a restart, repeat the process above, and I could connect via https://localhost:8000/. However, it refuses to connect more regularly now (like 8/10 times I start up for the day)
Connecting to https://127.0.0.1:8000 yields the same result.
Connecting to the site using the internal WSL IP address, found using hostname -I and replacing localhost with this IP (still on port 8000). This is an adequate workaround to use my app, however I am unable to interact with my database via MySQL Workbench without having to set up a new connection, therefore a fix where I can use localhost would be very helpful!
(Based off comments) Only ran symfony serve -d without starting apache and PHP services separately - still sometimes allows connections to localhost but sometimes doesn't work.
Conclusion
The behaviour is odd as it works sometimes but other times it doesn't when the exact same steps are carried out. I am unsure where else to look for answers and I can't seem to find anything online with this same problem. Please let me know if any config files, etc would be helpful. Thank you so much for your help! :)
When it's working normally, as you are clearly aware, the "localhost forwarding" feature of WSL2 means that you can access services running inside WSL2 using the "localhost" address of the Windows host.
Sometimes, however, that feature breaks down. This is known to happen when you either:
Hibernate
Have the Windows "Fast Startup" feature enabled (and it is the default). Fast Startup is a pseudo-hibernation which triggers the same problem.
Typically the best solution is to disable Hibernation and Fast Startup. However, if you do need these features, you can reset the WSL localhost feature by:
Exiting any WSL instances
Issuing wsl --shutdown
Restarting your instance
It's my experience that localhost forwarding will work after that. However, if it doesn't, thanks to #lwohlhart in the comments for mentioning that another thing to try is disabling IPv6 on WSL2, since (I believe) there's a possibility that the application is listening on IPv6 while the Windows->WSL2 connection localhost connection is being attempted on IPv6.
You can disable IPv6 on WSL2 per this Github comment by creating or editing .wslconfig in your Windows user profile directory with the following:
[wsl2]
kernelCommandLine=ipv6.disable=1
A wsl --shutdown and restart will be necessary to complete the changes.
If you find that this works, it may be possible to solve the issue by making sure to either use the IPv4 (127.0.0.1) or IPv6 (::1) address specifically in place of localhost on the Windows side, or by configuring the service to listen on both addresses.
Try to run command netstat -nltp. It shows active addresses and ports. Your nginx process should be run at 0.0.0.0:8000. 0.0.0.0 means the nginx process is available from anywhere.
If your nginx process is ran by any specific ip address, you should access it by that ip address, e.g http://192.168.4.2:8000.

Putty error : Unable to open connection to hostname : Host does not exist

I am using Putty to ssh into some of the servers that I work on. I am able to connect all others except the one. Although I was able to connect to it before. Whenever I try connecting to it, it always give me error:
Unable to open connection on myhost: Host does not exist
My firewall is off and I have even re-installed putty but that did not fix it. When I tried connecting to the same server using putty on some other windows system, I was able to do so. I searched regarding this on Internet but did not find much relevant.
I am running putty on Windows 7.
What can be the possible issue?
As I understand you have three computers involved. At the same time one connection is working and the other one fails. So we can exclude that the ssh daemon on your linux box is hanging.
In lack of knowing their real names I will call your computers linuxbox (this is the computer you want to ssh into), win7ok (that is the computer that you are able to ssh from using putty) and win7fail (that obviously is the computer you can't connect from).
Please do a tracert from both Win7 computers:
tracert linuxbox.your.domain
tracert linuxbox
Add the results to your question as it will help us find out what is happening.
Perhaps it is also a good idea to determine the ip address of the linuxbox from win7ok:
ping linuxbox
or
nslookup linuxbox
Then try to connect from win7fail by using the ip address of the target computer, perhaps it is only a DNS problem (which might be as nmap is failing too).
To make all of this easier to understand for us please provide the real names of the computers as you use them in putty.
For me the problem was with the Url of the reposity. Check remote URL. It must start with git#github.com, not https://.
I used nslookup and then used the ip address it gave me to connect and it worked
I had a similar problem with GitExtensions. The solution was to remove the https url and replace it with git#gitlab....
WRONG:
GOOD:
I just went through this. I have a Cisco VPN I need to use to get through to the Linux machine I wanted to login to and check.
No Putty session would get through using the machines name.
An nslookup on the windows machine yielded the correct address.
I too connected right in via the ip address.
I tried to Google the error and it failed, so I suspected the wireless.
Disconnected and reconnected my WiFi and all was good.
I did it fast enough that open connections stayed open.
And new connections refering to DNS names worked fine.
Seems like maybe some cached DNS addresses were stale.
Your DNS cache stores the locations (IP addresses) of web servers that contain web pages which you have recently viewed. If the location of the web server changes before the entry in your DNS cache updates, you can no longer access the site.
Following CLI command will do the trick:
ipconfig /flushdns

X forwarding through NAT

I'm trying to install Oracle 11g from scratch on an AWS Linux machine. In order to do so, I believe I'm required to enable X forwarding so I can use the graphical installation. I have never been good with X server/client situtations.
Setup:
cygwin64 (local)
NAT instance (Amazon)
Linux instance in private subnet accessible through said NAT (Amazon)
I'd like to forward the Oracle installation from the Linux instance through the NAT and to my local machine. Any help would be appreciated. I'm happy to provide more information, especially since I haven't provided much so far. I'd also love to hear that I'm going about this all wrong and that it's easy to install Oracle from the command line.
The client and server seem "backwards" in the world of X, because your workstation is the "server," providing the service of a display device and keyboard/mouse... while the program you are running, often remotely, is the "client," using those display and input devices services.
So the program you want to run needs to be able to connect "backwards" to your machine, but you can forget, for a moment, about the NAT aspect, because that's not directly relevant. The important thing is that you have a way to establish a chain of SSH connections from end to end, and that should be all you'd need, because SSH does the work. No firewalls were harmed in the answering of this question.
I don't know what kind of SSH utility cygwin has, but it will presumably be comparable. I tested the following first when end to end Linux, and then by replacing "ssh" with "\Program Files (x86)\PuTTY\putty.exe" on a Windows 7 desktop machine for the workstation. Both scenarios worked as expected, and the arguments are conveniently the same.
We'll call the NAT machine hostname "natbox" and the database "databox".
On your local machine, your X server is presumably listening on port 6000, so we need to get traffic back to it.
workstation $ ssh -R 127.0.0.1:5555:127.0.0.1:6000 natbox
I chose 5555 arbitrarily, but any unused value above 1024 should work. You could also use 6000 also but it makes the example even more counter-intuitive than it already is.
The first IP/port pair 127.0.0.1:5555 refers to the remote machine (natbox). Your SSH session will open a socket listening on port 5555 of the the loopback interface on the remote machine. The second IP/port pair 127.0.0.1:6000 refers to your workstation, which is the place the traffic is to return to. Connections to port 5555 on "natbox" will be tunneled back on your workstation, where an attempt will be made to connect to your local port 6000.
natbox $
So now we're logged in to natbox, and the tunnel is half-built.
natbox $ ssh -R 127.0.0.1:6000:127.0.0.1:5555 databox
This makes an SSH connection to "databox" where it opens up a listen socket on that server's port 6000 bound to the loopback address. Connections hitting that port will be sent back down the ssh connection to "natbox" where they will try to connect to natbox's port 5555... which, in the prior step, we already have linked back to your workstation's port 6000 -- your X server.
databox $ export DISPLAY=:0.0
databox $
Done.
Any X client program run on "databox" will try to connect to the local machine's display '0' on port 6000... which should end up back at your console.
databox $ xterm
This should open up a terminal window from "databox" on your local display. You don't need this, but it's probably going to be easier to verify and troubleshoot the X setup without dragging the Oracle componentry into the mix.
Note, the first reference to 127.0.0.1 (and the : between it and the first port number) on the ssh -R option are actually implicit, but I included them because it seems slightly less counter-intuitive to me. It is also possible to set this up in a cascade on a single command line, by providing the "command to execute" on the intermediate machine as the final argument to "ssh" on the local machine, as long as you add a -t to the first ssh so that it knows you want a tty end-to-end... but it was already complicated enough, so I didn't include that.

How to access vhosts via IPad?

I'm using XAMPP, on Mavericks, to simulate a localhost. I set jobeet.local, for example, as my vhosts. I tried to access it on my computer, it worked as well.
Now, I want to test my website on an IPad. So, I did the following steps:
Run XAMPP server on port 80, as usual
Connect the IPad to my wifi network.
Setup Http Proxy on Ipad, as picture showed below but change the port to 80
Now, I tested to access 127.0.0.1 via IPad. It worked! However, jobeet.local doesn't work.
I have searched and tried many ways to achieve this issue but they don't work.
Could you help me figure it out?
Thanks in advance.
You might have to update the hosts file.
The hosts file is a text file that maps hostnames to IP addresses.
Upon typing a url address on the browser, the system is checking if there is a relevant entry on the hosts file and gets the corresponding IP address, else it resolves the IP via the active connection’s DNS servers.
The hosts file can be edited to block certain hostnames (like ad-serving/malicious hosts), or used for web development purposes, i.e. to redirect domains to local addresses.
Editing the hosts file
Editing the hosts file in Mac OS X – Leopard, is a pretty easy task, especially if you are familiar with the terminal.
Step 1 – Open the Terminal.app
Either by start typing Terminal on the Spotlight, or by going into Applications -> Utilities -> Terminal.
Step 2 – Open the hosts file
Open the hosts by typing on the Terminal that you have just opened:
$ sudo nano /private/etc/hosts
Type your user password when prompted.
Step 3 – Edit the hosts file
The hosts file contains some comments (lines starting with the # symbol), as well as some default hostname mappings (e.g. 127.0.0.1 – localhost).
Simply append your new mappings underneath the default ones. Or edit one of the default values if you know what you are doing!
You can navigate the file using the arrow keys.
Step 4 – Save the hosts file
When done editing the hosts file, press control-o to save the file.
Press enter on the filename prompt, and control-x to exit the editor.
Step 5 – Flush the DNS cache
On Leopard you can issue a simple Terminal command to flush the DNS cache, and have your host file changes to take immediate effect:
$ dscacheutil -flushcache
You can now test your new mapping on the browser!
Hope this works for you!
I had to reinstall my setup today and made a step by step at that occasion:
I use a combination of Squidman and Mamp Pro (I assume it's similar to XAMPP)—hope this help anyone in their quest; happy to read feedback or get advice to make this better...
Squidman http://squidman.net/squidman/index.html
Mamp Pro http://www.mamp.info/en/mamp-pro/
on Squidman
- Preferences > General > Http port:
something different from the one MAMP is using (if map uses 80, then put 8080)
Preferences > Clients > Provide proxy service for:
insert the IP address or the subnet we will be catering for
Start Squidman
on MAMP:
setup the hostname, as well as the the website attached
insert the (local) IP address of the local machine
insert the port of Apache on the local machine
start Mamp; check that website is running correctly on local machine
on iPad/iPhone/mobile device
select the same wireless network as the laptop
in Wifi network > Preferences/Information: set a Manual HTTP Proxy
server IP is the (local) IP address of the Apache server, also running Squidman; port is the port used for Squidman
(Extra)
stuff to test: move dev server onto virtual machine (VirtualBox), to use with Node, custom PHP build, etc.
automate the setting: write pref for Squidman, Mamp/hostname, restart the Apache server, send configuration of proxy to mobile via iMessage or email.
I recommend using http://xip.io/. For example (taken from the website):
10.0.0.1.xip.io resolves to 10.0.0.1
www.10.0.0.1.xip.io resolves to 10.0.0.1
mysite.10.0.0.1.xip.io resolves to 10.0.0.1
foo.bar.10.0.0.1.xip.io resolves to 10.0.0.1
It does the job and you don't have to set anything up. I'm only pushing it because I am overly excited that I have wasted time trying over-engineered solutions.
On a mac you can use Squid on Windows that's Fiddler, however I'm having troubles with Fiddler and iPhone at the moment...

How to check programmatically the OS of remote host?

I need to check if remote host is Windows or Unix/Linux.
I can't assume that it has web server configured.
All I can do is to try to connect to several TCP or UDP services.
Which TCP services (TCP port numbers) usually will be opened on Windows and not on Unix/Linux and vise versa?
The other way is to try to ssh to it, and if it fails assume that it Windows host. The problem is, that I need this in order to choose the remote access method ssh or something Windows friendly like psexec.
You can read the output of nmap to detect which OS a remote host is running. It has a whole module dedicated to this. Here is a guide to using it.
Why not just try to connect one way, and if that fails, connect the other way, and if neither work, tell the user?
If that's all you're trying to do, there's no need to actually check the OS.
This is not an easy thing to answer with any degree of certainty as there are very few ports that will always be open on one OS but not on another.
You could try some/all of the following
80 http obviously
22,23 Telnet and SSH (Not usually open on windows, one at least usually open on *nix)
135 Used by WMI so often open on windows
1443 (Possibly SQL Server)
691 Used by MS Exchange routing
3389 MS Remote Desktop
I would suggest that scanning ranges of ports may lead you into trouble particularly if these are not your machines. You may find your IP address logged as a possible source of "Port Scanners"
There are some fairly extensive lists of ports available on the web. e.g. http://keir.net/portlist.html

Resources