Skip to content

Instantly share code, notes, and snippets.

@angus-mcritchie
Last active January 8, 2024 19:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save angus-mcritchie/c26a9002da89f52f7cdd7fa34956103f to your computer and use it in GitHub Desktop.
Save angus-mcritchie/c26a9002da89f52f7cdd7fa34956103f to your computer and use it in GitHub Desktop.
WSL2 Static IP Address (Windows Host Override)

WSL 2 Static IP Address (Windows Host Override)

A crude, but effective solution for hosting local development projects inside WSL 2.

before you start

  • node js is required
  • ⚠️ this script changes your host file - save a copy of your host file before use

Steps

1. Create C:\wsl\sync-wsl-ip.js

const { execSync } = require('child_process');
const fs = require('fs');

// Step 1: Get the latest WSL IP address
const wslIpAddress = execSync('wsl hostname -I').toString().trim().split(' ')[0];

// Step 2: Read the Windows host file
const hostFilePath = 'C:/Windows/System32/drivers/etc/hosts';
const hostFileContent = fs.readFileSync(hostFilePath, 'utf8');
const excludeRegex = /docker/;

// Step 3: Update the Windows host file with the latest WSL IP address
const updatedHostFileContent = hostFileContent
    .split('\n')
    .map(line => line.trim())
    .map(line => {

        if (excludeRegex.test(line) || line.charAt(0) === '#' || line === '') {
            return line;
        }

        const domain = line.split(/\s+/).slice(-1)[0];

        return `${wslIpAddress} ${domain}`;
    })
    .join('\n');

fs.writeFileSync(hostFilePath, updatedHostFileContent, 'utf8');

Now, you can open up the terminal and use node "C:\wsl\sync-wsl-ip.js to update all the IP addresses in your windows host file to your current WSL IP address.

2. (optional) Create a shortcut for easy useage

In C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup, create a mew shortcut called Sync WSL IP and set the target to a new file called C:\wsl\sync-wsl-ip.bat with the following contents.

node "C:\wsl\sync-wsl-ip.bat"

3. (optional) Add any non-WSL domains to the excludeRegex

const excludeRegex = /docker|my-windows-only-project/;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment