Skip to content

Instantly share code, notes, and snippets.

@samlovescoding
Created April 9, 2024 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samlovescoding/c57db8ac3afb7ab8d60210cf1df2045b to your computer and use it in GitHub Desktop.
Save samlovescoding/c57db8ac3afb7ab8d60210cf1df2045b to your computer and use it in GitHub Desktop.

https://stackoverflow.com/questions/8652948/using-port-number-in-windows-host-file

I managed to achieve this by using Windows builtin networking tool netsh.

As Mat points out: The hosts file is for hostname resolution only, so a combination of the two did the trick for me. Example Overview

example.app:80 | <--Link by Hosts File +--> 127.65.43.21:80 | <--Link by netsh Utility +--> localhost:8081

Actions

Started my server on localhost:8081

Added my "local DNS" in the hosts file as a new line

127.65.43.21     example.app

    Any free address in the subnet 127.0.0.0/8 (127.x.x.x) can be used.
    Note: I am assuming 127.65.43.21:80 is not occupied by another service.
    You can confirm this by checking the output of netstat -a -n -p TCP | grep "LISTENING"

Added the following network configuration, using netsh:
netsh interface portproxy add v4tov4 listenport=80 listenaddress=127.65.43.21 connectport=8081 connectaddress=127.0.0.1

I can now access the server at http://example.app

Notes:

These commands/file modifications need to be executed with Admin rights
netsh portproxy needs IPv6 libraries, even just to use v4tov4. Typically these will be installed by default, otherwise install with netsh interface ipv6 install

You can see the entry you have added with the command:

netsh interface portproxy show v4tov4

You can remove the entry with the following command:

netsh interface portproxy delete v4tov4 listenport=80 listenaddress=127.65.43.21

Links to Resources:

Using Netsh
Netsh commands for Interface IP
Netsh commands for Interface Portproxy
Windows Port Forwarding Example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment