How to connect to a local machine from WSL?

Abstract: Resolve host machine IP from WSL2 using host.docker.internal or gateway address to enable seamless SSH connectivity.

Created: 2026-09-18 by
To connect from Windows Subsystem for Linux (WSL) to your host machine, you must use the special DNS name host.docker.internal or query the network interface IP address. This approach bypasses standard localhost loops by targeting the virtual network adapter that bridges WSL2 with Windows. By configuring SSH keys and verifying connectivity, you can seamlessly manage files and execute commands across both environments without manual IP lookups.

Understanding the Network Architecture

WSL2 runs inside a lightweight utility VM, which means it has its own private IP address on a virtual switch. Unlike WSL1, localhost in WSL2 does not automatically map to the Windows host's loopback interface. Instead, Microsoft provides a specific mechanism to resolve the host machine's address. The most reliable method is using the DNS name host.docker.internal, which resolves to the IP address of the Windows host as seen from within the WSL2 environment. Alternatively, you can find the specific IP assigned to the virtual Ethernet adapter by inspecting the routing table.

Determining the Host IP Address

If you prefer explicit IP addressing over DNS resolution, you can retrieve the gateway IP address which corresponds to your Windows host. Open your WSL terminal and run the following command:

ip route | grep default

The output will display a line similar to default via 172.x.x.x dev eth0. The IP address following via is the address of your Windows host machine on the virtual network. You can use this IP directly in your SSH commands. Note that this IP may change if the WSL instance is restarted or if the network configuration changes, so storing it in a variable or using the DNS name is often more robust for scripting.

Configuring SSH for Seamless Access

Once you have identified the correct address, the next step is ensuring that SSH authentication works smoothly. Manually entering passwords every time you connect is inefficient. Instead, configure SSH keys to allow passwordless login between WSL and Windows. First, generate an SSH key pair in WSL if you do not already have one:

ssh-keygen -t ed25519 -C "wsl-to-windows"

Next, copy the public key to the Windows side. You can do this by piping the content of the public key file into the clipboard and pasting it into the authorized_keys file on Windows, or by using the ssh-copy-id command if configured correctly. On Windows, ensure the SSH service is running and that the authorized_keys file exists in the %USERPROFILE%\.ssh\ directory. This setup allows you to connect instantly without interactive prompts.

Creating an SSH Alias

To simplify connections further, add an entry to your ~/.ssh/config file in WSL. This eliminates the need to type long IP addresses or usernames repeatedly. Add the following block:

Host winhost
    HostName host.docker.internal
    User YourWindowsUsername
    IdentityFile ~/.ssh/id_ed25519
    Port 22

Replace YourWindowsUsername with your actual Windows account name. After saving this file, you can connect simply by typing ssh winhost. This alias approach is particularly useful when managing multiple local services or when switching between different development environments.

Verifying Connectivity and Troubleshooting

After configuration, test the connection by running ssh winhost. If the connection fails, check several common issues. First, verify that the SSH server is installed and enabled on Windows. In newer versions of Windows 10 and 11, you can enable the OpenSSH Server feature through the Settings app under Apps > Optional Features. Ensure that the firewall allows inbound connections on port 22. If you are using a different port, update the Port field in your SSH config accordingly.

Another frequent issue involves DNS resolution. If host.docker.internal does not resolve, try pinging the IP address obtained earlier. If the ping succeeds but SSH fails, the problem likely lies in SSH configuration or permissions rather than network reachability. Check the Windows Event Viewer for SSH-related errors if the connection drops unexpectedly. For advanced networking scenarios, such as forwarding ports from WSL to Windows, refer to our guide on Troubleshooting SSH: Unable to Forward Dynamic Port to Host for detailed diagnostics on port mapping issues.

Alternative Connection Methods

While SSH is the standard protocol for remote command-line access, other methods exist depending on your needs. For file sharing, you can access Windows drives directly from WSL via the /mnt/c/ mount point, eliminating the need for network transfers for local files. However, for remote execution or accessing services bound to localhost on Windows, SSH remains the most efficient tool. If you need to expose WSL services to Windows, you can bind them to 0.0.0.0 instead of 127.0.0.1 to make them accessible from the host network. This bidirectional connectivity ensures a flexible development environment where both systems can interact freely.

For users interested in securing their network access further, especially when dealing with multiple devices, understanding access control is crucial. See Shutting Down Multiple Raspberry Pi Linux Systems: Network SSH Access Control for insights on managing permissions and restricting access based on user roles and network segments.

Frequently Asked Questions

Why does localhost not work in WSL2?

Localhost does not work because WSL2 runs in a separate virtual machine with its own network stack. The loopback interface in WSL2 points only to itself, not to the Windows host. You must use the specific bridge IP or the host.docker.internal DNS name to reach Windows services.

Can I use SSH to run GUI applications from WSL on Windows?

Yes, you can use X11 forwarding to display Linux GUI applications on your Windows desktop. You need an X server like VcXsrv or MobaXterm running on Windows. Configure your WSL SSH client to request X11 forwarding by adding -X to your ssh command or setting ForwardX11 yes in your config file.

How do I handle dynamic IP changes in WSL2?

WSL2 IPs can change upon restart. Using host.docker.internal handles this automatically as it resolves dynamically. If you use static IPs, you can write a script to detect the new IP and update your SSH config or aliases automatically each time WSL starts.

Is it safe to expose SSH to the entire network?

Exposing SSH broadly increases security risks. It is safer to restrict access to specific IP ranges or use key-based authentication exclusively. Disable password authentication in the Windows SSH server configuration to prevent brute-force attacks. Always keep your SSH server software updated to patch known vulnerabilities.

What if I cannot install OpenSSH Server on Windows?

If you cannot install the server due to organizational policies, consider using alternative protocols like SCP or SFTP if available. Another option is to use PowerShell remoting or WinRM for management tasks, though these require different client configurations compared to standard SSH clients.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More