This is part 2 in series on Windows Network Load Balancing. Part 1 can be found here: https://blog.workinghardinit.work/2010/07/01/reflections-on-getting-windows-network-load-balancing-to-work-part-1/
On Default Gateways, Routing & Forwarding.
Here’s a bullet list of what people tend to trip over when configuring NLB network settings.
Now let’s address the subjects in this list.
No support for multiple Default Gateways that are on multiple subnets
When using IP addresses from different subnets you cannot have a default gateway on every NIC because that will cause routing issues. This is not different for the NIC’s used in Windows NLB. So you can have only one NIC with a Default Gateway and if the other NICs need to route somewhere you need to add static persistent routes. Those routes must be persistent or they will not survive a reboot of the server. In the figure below you see a classic two NIC NLB cluster with the Default Gateway Empty on the NLB NIC. This could be a valid setup for an intranet. You can add routes for the subnet in the company that need to be able to talk to the NLB Cluster and you’re golden. The Private NIC gets a default gateway and acts like any other NIC in your network.
In this example we have the Default Gateway on the Private NICs they can route internally and to the internet. If you need traffic to & from the internet form the NLB NIC you could enable forwarding on the NLB NIC or enable weak host behavior which can be done more atomic than what you achieve by enabling forwarding. If you only need to route internally we could use the same approach of enabling forwarding instead of adding static persistent routes for the NLB NIC. But then you don’t isolate & protect traffic that neatly and it will route to everywhere the default gateway can get.
So we prefer to play with static persistent routes in this case. We’ll briefly look at some examples now. If you only need to route internally (i.e. to reach the database or a client PC) from the NLB NIC we add the needed static persistent routes on the NLB NICs using the route command.
In order for the NLB NICs to reach the database with strong host model and no forwarding enabled:
Route add -p 10.30.0.0 mask 255.255.0.0 10.10.0.1
To reach the client PC’s:
Route add -p 10.20.0.0 mask 255.255.0.0 10.10.0.1
(Using route print you can look at the routes and using route delete you can get rid of them.)
Or by using netsh, (it’s advised to use netsh from Windows 2008 on)
netsh interface ipv4 add route 10.30.0.0/16 “NLB NIC” 10.10.0.1
netsh interface ipv4 add route 10.20.0.0/16 “NLB NIC” 10.10.0.1
You could also connect to the database over the PRIVATE NIC and then you don’t need that route. If you can configure it like that it’s a good solution. But all situations differ.
You can also play with the weakhost / stronghost model behaviour:
netsh interface ipv4 set interface Private NIC weakhostsend=enabled
netsh interface ipv4 set interface Private NIC weakhostreceive=enabled
netsh interface ipv4 set interface NLB NIC weakhostsend=enabled
netsh interface ipv4 set interface NLB NIC weakhostreceive=enabled
Now don’t just blindly enable on every NIC you can find on the server. Test what you really need and use only that. I leave that as an exercise to the readers. It really depends on the situation and needs for your particular situation. Keep in mind that when you enable weakhostsend and weakhostreceive on every NIC this reverts your Windows 2008 servers back to Windows 2003 behavior and this might not be needed or wanted. So just enable what you need for optimal security.
Naturally enabling forwarding will do the trick as well, as this creates a weak host model. Depending on how many NICs you use and how traffic must flow you might have to do it on more than one NIC, normally the one(s) without a default gateway.
netsh interface ipv4 set interface “NLB NIC” forwarding=enabled
If you want to see the configuration of the NIC you can run:
netsh interface ipv4 show interface l=verbose
That will produce something like below:
Interface Local Area Connection Parameters
IfLuid : ethernet_5
IfIndex : 3
State : connected
Metric : 10
Link MTU : 1500 bytes
Reachable Time : 21500 ms
Base Reachable Time : 30000 ms
Retransmission Interval : 1000 ms
DAD Transmits : 3
Site Prefix Length : 64
Site Id : 1
Forwarding : disabled
Advertising : disabled
Neighbor Discovery : enabled
Neighbor Unreachability Detection : enabled
Router Discovery : dhcp
Managed Address Configuration : enabled
Other Stateful Configuration : enabled
Weak Host Sends : disabled
Weak Host Receives : disabled
Use Automatic Metric : enabled
Ignore Default Routes : disabled
Advertised Router Lifetime : 1800 seconds
Advertise Default Route : disabled
Current Hop Limit : 0
Force ARPND Wake up patterns : disabled
Directed MAC Wake up patterns : disabled
The default gateway does not have to be empty on the NLB NIC
It is not a hard requirement to leave the Default Gateway on the NLB NIC empty and put it on the private NIC. You can set it on the NLB NIC and leave the private NIC’s gateway empty instead. An example of this you can see in the demo. This is the best choice in my opinion when you need the NLB NIC to route to destinations you don’t know how to reach, i.e. the internet, so for public websites. The prime function of the default gateway is exactly to help with that. When you don’t know where to send it, send it to the Default Gateway. If you need to reach other internal subnets from the Private NIC, just use static routes. Don’t use the NLB NIC as that is internet facing in this case. You can see an example of this in the figure below. Also in this case you’ll find that you do not have to enable forwarding on the NIC using netsh, as the NIC that has to answer to the unknown IP Address has the Default Gateway. This setup works great for example in a managed domain environment for internet access where the NLB NICs are internet facing and the private NIC is for management, Active Directory, Backups, etc.
In this example we have the Default Gateway on the NLB NICs so it can route internet traffic. Any routes needed in the Private NIC subnet are added as persistent static routes. An example of this is to reach the database server.
As traffic from the Private range is never supposed to go via the NLB Public range and vice versa we do not need to care about forwarding or strong host /weak host models. We can keep traffic nicely separated and that is a good thing. If you build this on Windows 2008(R2) just like you did on Windows 2003 it would work out of the box and you might not even know about a change in default behavior from weak host model to strong host model.
To get the PRIVATE NIC to reach the database server you’d add static routes and be done with it.
Add needed static persistent routes using the route command:
Route add -p 10.20.0.0 mask 255.255.0.0 172.16.2.1
netsh interface ipv4 add route 10.20.0.0/16 “PRIVATE NIC” 172.16.2.1
No requirement to have different subnets for Private and NLB NICs / Multiple Gateways When the subnets are the same
There is no requirement to have different subnets for every NIC. Sometimes I read that this is a requirement on forums when someone is having issues but it’s not. You can also experiment with multiple Default Gateways if they are on the same subnet
So here you can play with giving every NIC a default gateway (same subnet, so no issues), with static persistent routes, with enabling forwarding and weak host / strong host configuration. I tend to use only one gateway and use static persistent routes. If I need to relay I’ll go for weak host minimal configuration or revert to forwarding.
It’s also smart not to mix static routes with forwarding to achieve the same thing. And please have the exact same configuration on very particular NIC on every node. Not one node with NLB NIC 1 routing via static routes and the other node using forwarding on NLB NIC 1. That’s asking for inconsistent behavior.
If you only need to route internally (i.e to reach the database or a client PC) we add the needed static persistent routes on the NLB NICs using the route command.
You can also just enter the default gateway on the NLB NICs as well. All NICs are on the same subnet this will cause no issues. Just remember that traffic will also go to where ever that gateway routes, even to the internet.
We already know we can play with the weakhost / stronghost model:
Again don’t just blindly enable on every NIC you can find on the server. Test what you really need and use only that. I leave that as an exercise to the readers. As I’ve said before, it really depends on the situation and needs for your particular situation. Keep in mind that when you enable weakhostsend and weakhostreceive on every NIC this will just revert your Windows 2008 server into Windows 2003 behavior and this might not be needed or wanted. So just enable what you need for optimal security.
There is a very good explanation of strong and weak host behavior by “The Cable Guy” at I strongly advise you to go take a look.
And naturally enabling forwarding will do the trick in this scenario as well, as this creates a weak host model. Depending on how many NICs you use and how traffic must flow you might have to do it on more than one NIC, normally the one(s) without a default gateway.
When & Why Use Three NICs or more?
NLB supports using multiple network adapters to configure separate clusters. This allows for configuring multiple independent clusters on each host. We used to have only virtual clusters meaning that you could configure multiple clusters on a single network adapter. Anyone who ever had to trouble shoot some networking or configuration issues on a production NLB will appreciate the ability to limit interruptions and problems to one cluster instead of 2 or more. As an example of this I had to trouble shoot a CAS/HUB Exchange Implementation two node NLB implementation. The NLB Cluster of the CAS role had this very issue, but since it was running on its own cluster with a separate NIC the HUB role NLB cluster has no issues what so ever. Another good reason to use more NIC is to separate traffic, for example FTP versus HTTP on the same NLB Cluster.
One of the worst things that can happen is that an issue messes up the proper functioning of the NLB itself. That way even if the virtual IP remains available no host or only some of the hosts get network traffic. That means the cluster is unavailable or is only partially responding. This is a bad situation to be in and can be hard to trouble shoot. Since it’s a high availability technology you can bet someone is looking over your shoulder that has a vested interest in getting that resolved as soon as possible.
Mind the order of the connections in Adapters and Bindings
Conclusion & recapitulation
I’ll finish with some closing musings on single & multiple default gateway and getting/sending network traffic where it needs to go.
When you enter a gateway on the second, third and so on NIC next to the one on the first NIC you’ll get a warning:
Warning – Multiple default gateways are intended to provide redundancy to a single network (such as an intranet or the Internet). They will not function properly when the gateways are on two separate, disjoint networks (such as one on your intranet and one on the Internet). Do you want to save this configuration?
This will not work reliable when you have multiple subnets. This is why you use static persistent routing entries. Depending on your needs you can also use forwarding or the weak host model and even combine those with static persistent routes if needed of desired. Now the above also means that if you have multiple NICs with IP addresses on the same subnet you can indeed enter a Default Gateway on all of them.
If you don’t have or cannot have a Default Gateway filled in you are left with two options. If you know what needs to go where you can add static routes, which is basically telling the NIC the IP of a gateway to send traffic to for a certain destination. This is assuming you can reach that IP and that the traffic is not from a source/ to a destination that has no route defined and firewall allow for it, etc.
Contact me via the web site or leave a comment if you have any questions or suggestions.
here is a set of netsh command lines which I use very often.
Show Interface configuration
netsh interface ipv4 show config
Only IP Addresses of all LAN adapters
netsh interface ipv4 show address
Show global TCP/IP Parameters
netsh interface ipv4 show global
Show all network interfaces and its link state
netsh interface ipv4 show interfaces
Print the routing table
netsh interface ipv4 show route
Show all tcp connections
netsh interface ipv4 show tcpconnections
Which Multicast groups are joined
netsh interface ipv4 show joins
Show dynamic portrange for outgoing connections
netsh interface ipv4 show dynamicportrange protocol=tcp
Set a static IP Address (172.16.254.2), Subnet Mask (255.255.255.192) and Gateway (172.16.254.1) on a specific interface (Local Area Connection 2) persistent
netsh interface ipv4 set address name=”Local Area Connection 2″ static 172.16.254.2 255.255.255.192 172.16.254.1 store=persistent
and temporary up to the next reboot and the parameters at full length. After the reboot the IP Address is empty.
netsh interface ipv4 set address name=”Local Area Connection 2″ static address=172.16.254.2 mask=255.255.255.192 gateway=172.16.254.1 store=active
Set DNS Servers without a DNS check, the set dnsservers command supports only one server as argument
netsh interface ipv4 set dnsservers name=”Local Area Connection 2″ source=static address=”172.16.254.250″ validate=no
you have to add a second DNS Server with the add dnsservers directive
netsh interface ipv4 add dnsservers name=”Local Area Connection 2″ address=”172.16.254.251″ validate=no index=2
Set IP Address assignment on Interface to DHCP
netsh interface ipv4 set address name=”Local Area Connection 2″ source=dhcp
and also the DNS Servers
netsh interface ipv4 set dnsservers name=”Local Area Connection 2″ source=dhcp
Add a route for subnet 172.16.1.0/24 over interface “Local Area Connection 2” and router 172.16.254.254
netsh interface add route prefix=172.16.1.0/24 interface=”Local Area Connection 2″ nexthop=172.16.254.254
Note: Since Windows Vista its not possible to set the dns search suffix with netsh, you have to use WMI for this.
To set the DNS search suffix use powershell and wmi.
Define your Domains
Get the WMI Class to invoke the static method SetDNSSuffixSearchOrder
Or invoke the method directly by calling the Invoke-WmiMethod commandlet
Note: If the aDNSSearchSuffixes Array contains more then one element a second parameter of $null is requiered otherwise the Invoke-WmiMethod command failed with error: Invoke-WmiMethod : Unable to cast object of type ‘System. String’ to type ‘System. Array’.
Advertisment to support michlstechblog.info
В современных версиях Windows есть интересная возможность автоматического добавления статических маршрутов при активации определённого VPN подключения. Когда VPN подключение разрывается, данный маршрут автоматически удаляется из таблицы маршрутизации Windows. Для добавления IPv4 или IPv6 маршрута для VPN подключения используется PowerShell командлет Add-VpnConnectionRoute.
Вы конечно, можете вручную в командной строке добавлять нужные маршруты для VPN подключения, но главная проблема в том, что такие маршруты очищаются после отключения от VPN. Поэтому при следующем подключении, вам придется опять руками прописывать маршруты.
Допустим, вы хотите, чтобы через ваше VPN подключение маршрутизировались только пакеты для двух подсетей (192.168.111.24/ и 10.1.0.0/16), а весь основной трафик должен идти через вашего провайдера.
Откройте консоль PowerShell и выведите список всех настроенных VPN подключений в Windows:
В первую очередь нужно отключить опцию “Use default gateway in remote network” (Использовать основной шлюз в удаленной сети). Это можно сделать в свойствах VPN подключения в панели управления или командой:
Set-VpnConnection –Name workVPN -SplitTunneling $True
Подробнее про SplitTunneling здесь.
Добавим два статических маршрута для нашего VPN-соединения:
Add-VpnConnectionRoute -ConnectionName “workVPN” -DestinationPrefix 192.168.111.0/24 –PassThruAdd-VpnConnectionRoute -ConnectionName “workVPN” -DestinationPrefix 10.1.0.0/16 –PassThru
В параметре DestinationPrefix нужно указать подсеть, или конкретный IP адрес хоста, трафик к которому нужно маршрутизировать через VPN. Для добавления одного IP адреса используйте формат 10.1.1.26/32.
DestinationPrefix : 192.168.111.0/24
InterfaceIndex :
InterfaceAlias : workVPN
AddressFamily : IPv4
NextHop : 0.0.0.0
Publish : 0
RouteMetric : 1
Если у вас активно VPN подключение, вам нужно переподключиться, чтобы новые маршруты добавились в таблицу маршрутизации.
Новые маршруты привязаны к VPN подключению и добавляются при его запуске. Когда вы отключаетесь от VPN сервера, маршруты автоматически удаляются.
Отключитесь от VPN и проверьте таблицу маршрутизации. Маршрут к вашей удаленной сети удалился автоматически, а Get-NetRoute вернет, что маршрут не найден:
Get-NetRoute : No MSFT_NetRoute objects found with property ‘DestinationPrefix’ equal to ‘192.168.111.0/24’. Verify the value of the property and retry. CmdletizationQuery_NotFound_DestinationPrefix,Get-NetRoute
Display a list of static routes for connection:
(Get-VpnConnection -ConnectionName workVPN). Routes
To completely remove a static route for a VPN connection, use the command:
Remove-VpnConnectionRoute -ConnectionName workVPN -DestinationPrefix 192.168.111.0/24 -PassThru
If you need to change the order of DNS name resolution when VPN is active, check out the article.
In previous versions of Windows (Windows 7/ Server 2008R2), you had to use CMAK and various scripts with commands to dynamically add routes after establishing VPN connections
add route
.
For example, you can create a batch file vpn_route.netsh to add routes.
interface ipv4add route prefix=192.168.111.24 interface=”workVPN” store=activeadd route prefix=10.1.0.0/16 interface=”workVPN” store=activeexit
This file must be run through a scheduler task that is triggered by the VPN connection establishment event in the Event Viewer (RasMan 20225)
In this article, we will see how to set up a simple gateway router using the built-in server-based tools with Windows Server 2012 R2. And while computer-based routers are rarely used in practice (hardware routers tend to be faster, more reliable, and slightly cheaper than a dedicated computer), in test or virtual environments where you need to urgently set up routing between multiple subnets, a Windows-based router Server is quite an acceptable solution.
So, a server running Windows Server 2012 R2 will act as a router. The server has 2 network interfaces: physical or virtual if the server is running on a hypervisor. Each server interface is assigned a dedicated IP address from different subnets. For convenience, we have renamed the names of network interfaces in the Network and Sharing Control Panel:
Network card 1 (network card connected to internal LAN):
Network card 2 (network card in external network):
Our task is to organize the routing of packets from the local subnet 10.0.1.0 to the external subnet 192.168.1.0 (as a rule, such a network has access to the Internet) through NAT. Such a scheme can be implemented if it is necessary to organize access for clients from the internal network to the Internet.
Routing in Windows Server 2012 R2 is based on the Remote Access (RRAS) role. This service appeared back in Windows Server 2003 and until the current version of Windows Server, its interface and configuration process has not changed much.
After the installation is complete, open the Routing and Remote Access console (rrasmgmt.msc), click on the server name (with a red arrow) and select Configure and Enable Routing and Remote Access.
In the window that opens, select the Network Address Translation (NAT) item.
At the next step (NAT Internet Connection), you need to select the network interface connected to the external network / Internet (in our example, this is the Internet interface with ip 192.168.1.20). This interface will be the “public interface” of our NAT router.
Next, you will be prompted to specify whether the NAT router should provide internal network clients with DHCP and DNS services. As a rule, this functionality is already available in the internal network, so we do not need it.
This completes the basic routing setup on Windows Server 2012 R2. The server must already be routing packets between the two connected networks and performing Network Address Translation (NAT).
To verify this, open the server properties in the RRAS console. The General tab shows that IPv4 routing is enabled (i.e. IPv4 packets will be forwarded from one NIC to another).
Note. Windows Server 2012 R2 supports static routing, dynamic routing protocol RIPv2, and BGPv4. OSPF support was dropped back in Windows Server 2008.
In our case, static routing is implemented on the server. If you need to add a new route, right-click on Static Routes, select the New static route menu item and create a new static route rule.
Note. A static route can also be added from the command line using the Route or netsh commands.
In all versions of Windows, you can configure network port forwarding/forwarding (port forwarding) without using third-party tools. With a forwarding rule, you can redirect an incoming TCP connection (IPv4 or IPv6) from a local TCP port to any other port number, or even to a port on a remote computer. Port forwarding in Windows is most often used to bypass firewalls or to hide a server or service from an outside network (NAT/PAT).
On Linux it is quite easy to set up port forwarding quite simply with iptables or firewalld rules. On Windows Server systems, you can use the Routing and Remote Access Service (RRAS) to configure port forwarding. However, there is an easier way to set up port forwarding using the
portproxy
V
netsh
, which works equally well on any version of Windows (from Windows XP to modern Windows 11 and Windows Server 2022).
Enable port forwarding in Windows using netsh portproxy
You can enable and configure port forwarding in Windows from the command line through the Portproxy mode of the Netsh command.
The command syntax is as follows:
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport
where,
With options
netsh interface portproxy add
v4tov6
/
v6tov4
/
v6tov6
you can create port forward rules between or between IPv4 and IPv6 addresses.
Suppose our task is to force the RDP service to respond on a non-standard port, for example 3340 (this port, of course, can be changed in the settings of the service itself, but we use RDP to simplify the demonstration of port forwarding and redirection techniques). To do this, we need to redirect incoming traffic on TCP port 3340 to another local port – 3389 (this is the standard RDP port number).
Note. Note that the local port number you specify in listenport must not be occupied (listened on) by another service. Check that the port number is free with the command:
Or you can check that the port is not listening locally using the Test-NetConnection PowerShell cmdlet:
Test-NetConnection -ComputerName localhost -Port 3340
To create a port forwarding rule, run a command prompt as an administrator and run the following command: netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.10.1.110 connectport=3389 connectaddress=10.10.1.110
Where 10.10.1.110 is the IP address of your computer on which port forwarding is configured.
Note. If this command returns nothing and port forwarding via netsh interface portproxy does not work, check that you have the iphlpsvc service (IP Helper / IP Helper Service) enabled on your Windows.
Check the status of the service in the services.msc console or using the PowerShell command:
Also on the network interface for which the port forwarding rule is being created, support for the IPv6 protocol must be enabled.
These are mandatory conditions for the correct operation of port-forwarding. Without the IP Helper service and without IPv6 support enabled, the redirect mechanism does not work.
In Windows Server 2003 / XP, for redirection to work, you additionally need to enable the IPEnableRouter = 1 registry setting in the HKEY_LOCAL_MACHINE SystemCurrentControlSetservicesTcpipParameter branch. You can enable this registry setting using PowerShell:
Set-ItemProperty -Path HKLM:systemCurrentControlSetservicesTcpipParameters -Name IpEnableRouter -Value 1
This option also allows you to enable routing between different subnets in Hyper-V.
Now try to connect to the new port from a remote computer using any RDP client. You need to specify 3340 as the rdp port (the port number is indicated after the colon after the rdp server address). For example,
10.10.1.110:3340
In this example, port 3340 must first be opened in Windows Defender Firewall (see the next section of the article).
RDP connection should be established successfully.
Portproxy port forwarding rules are persistent and are not removed when Windows is restarted. These rules are stored in the registry. You can list the netsh redirect rules in the registry using PowerShell:
Get-ItemProperty -Path HKLM:SYSTEMCurrentControlSetServicesPortProxy 4tov4 cp
If you need to redirect an incoming TCP connection to a remote computer, use the following command:
netsh interface portproxy add v4tov4 listenport=3389 listenaddress=0.0.0.0 connectport=3389 connectaddress=192.168.1.100
It should be noted that the portproxy mode in Windows does not support storing the source IP in a forwarded network packet. Those. if you forward port 443 of a Windows computer to an internal web server, then on the target server all incoming connections will come from the same IP address (Windows computer with netsh portproxy enabled). If you need to use source IP forwarding, you need to use NAT on an external firewall or on Hyper-V (described below).
You can also use the SSH tunnel technique to forward a local port to a remote server in Windows.
Configuring Firewall Rules for Windows Port Forwarding Mode
Check that your firewall settings (Windows Firewall or 3rd party firewall, these are often included with antivirus software) allow incoming connections to the new port. You can add a new allow rule to Windows Defender Firewall with the command:
netsh advfirewall firewall add rule name=”RDP_3340” protocol=TCP dir=in localip=10.10.1.110 localport=3340 action=allow
Or using the New-NetFirewallRule PowerShell cmdlet:
New-NetFirewallRule -DisplayName “RDP_3340” -Direction Inbound -Protocol TCP –LocalPort 3340 -Action Allow -Enabled True
When creating an inbound firewall rule for port 3340 through the Windows Defender GUI, you do not need to associate a program or process with the rule. This port is listened exclusively by the network driver.
If you disable the portproxy rule, don’t forget to remove the remaining firewall rules like so:
netsh advfirewall firewall del rule name=”RDP_3340″
or using PowerShell:
Remove-NetFirewallRule -Name RDP_3340
Managing netsh port forwarding rules in Windows
You can create any number of Windows local port forwarding rules. All netsh interface portproxy rules are persistent and remain on the system after a Windows restart.
Several times I encountered cases when in Windows Server 2012 R2 the port forwarding rules were reset after the server was rebooted. In this case, it is recommended to check whether there are periodic disconnections on the network interface, and whether the IP address changes when the OS boots (it is better to use a static IP instead of dynamic DHCP). As a workaround, I had to add a script with rules to the Windows scheduler
netsh interface portproxy
, which creates a port forwarding rule when the operating system boots.
To display a list of all active TCP port forwarding rules in Windows, run the command:
netsh interface portproxy show all
In our case, there is only one forwarding rule from local port 3340 to 3389:
Listen on ipv4: Connect to ipv4:
Address Port
——————————————————-
10.10.1.110 3340 10.10.1.110 3389
Council. You can also display the weight of a port forwarding rule in portproxy mode like so:
netsh interface portproxy dump
#========================
# Port proxy configuration
#========================
pushd interface portproxy
reset
add v4tov4 listenport=3340 connectaddress=10.10.1.110 connectport=3389
popd
# End of Port Proxy configuration
If you need to change the settings of an existing portproxy rule, use the following command:
netsh interface portproxy set v4tov4 listenport=3340 listenaddress=10.10.1.110 connectport=3300 connectaddress=10.10.1.110
In this example, we have changed the portproxy target port address to 3300.
To delete a specific port forwarding rule, run: netsh interface portproxy delete v4tov4 listenport=3340 listenaddress=10.10.1.110
To remove all existing forwarding rules and completely clear the table with port-forwarding rules: netsh interface portproxy reset
Important. This redirection scheme only works for TCP ports. Traffic on UDP ports cannot be forwarded using the portproxy mode. You also cannot use localhost 127.0.0.1 as the connectaddress.
If you want to enable redirection of UDP traffic, you can use Windows Server with RRAS role and NAT. You can set up port forwarding between computer interfaces using the graphics snap-in (
rrasmgmt.msc
) or command:
netsh routing ip nat add portmapping Ethernet udp 0.0.0.0 53 192.168.1.54 53
The list of NAT port forwarding rules in Windows Server can be displayed like this:
netsh routing ip nat show interface
If you have WSL (Windows Subsystem for Linux) deployed on your computer, you can create a simple PowerShell script to create a port forward rule inside the WSL 2 virtual machine (the WSL 2 VM has its own virtual ethernet adapter with a unique IP address):
wsl –shutdown;netsh interface portproxy reset;$wsl_ipaddr = wsl -d Ubuntu-20.04 hostname -I;netsh interface portproxy add v4tov4 listenport=443 listenaddress=0.0.0.0 connectport=443 connectaddress=$wsl_ipaddr ;netsh interface portproxy show all;exit;
Another implicit feature of portproxy is the ability to create the appearance of local operation of any remote network service. For example, you want to forward all traffic from local port 9090 to
netsh interface portproxy add v4tov4 listenport=9090 listenaddress=127.0.0.1 connectaddress=142.250.74.46 connectport=443 protocol=tcp
Now, if you navigate to https://localhost:9090 in your browser (you need to ignore SSL_ERROR_BAD_CERT_DOMAIN errors), the Google search page will open. Those. despite the fact that the browser accesses the local computer, it opens a page from an external web server.
Port forwarding can also be used to forward a port from the external IP address of the network card to the port of a virtual machine running on the same computer. In Hyper-V, this port forwarding can be configured on the virtual switch (see below).
Windows cannot forward a range of TCP ports. If you need to forward multiple ports, you will need to manually create multiple forwarding rules.
Configuring Port Forwarding with NAT on Hyper-V Server
If you use the Hyper-V role on your computer (can be installed on both Windows 10/11 and Windows Server or as a free Windows Hyper-V Server), you can configure DNAT port forwarding using PowerShell. Let’s say you want to redirect all https requests that your Hyper-V host receives to the IP address of a virtual machine running on the host. This is done using the Hyper-V StaticMapping commands.
Create a Hyper-V virtual switch:
New-VMSwitch -SwitchName “NAT_Switch” -SwitchType Internal
Set the IP address for the new virtual switch:
New-NetIPAddress -IPAddress 192.168.10.1 -PrefixLength 24 -InterfaceAlias ”vEthernet (NAT_Switch)”
Enable NAT for this network:
New-NetNat -Name NATNetwork -InternalIPInterfaceAddressPrefix 192.168.10.0/24
Connect the VM to your NAT_Switch and set a static IP address for it (for example, 192.168.10.80). As the default gateway, you need to specify the IP address of the Hyper-V virtual switch (192.168.10.1).
You can now configure port forwarding from the Hyper-V host to the virtual machine:
Add-NetNatStaticMapping -NatName NATNetwork443 -Protocol TCP -ExternalIPAddress 0.0.0.0/24 -ExternalPort 443 -InternalIPAddress 192.168.10.80 -InternalPort 443
After executing these commands, all HTTPS traffic that comes to the TCP/443 port of the hypervisor will be forwarded to the gray IP address of the virtual machine.
If you want to forward a non-standard port, don’t forget to open it in Windows Firewall:
New-NetFirewallRule -DisplayName “HyperV_Nat_443” -Direction Inbound -LocalPort 443 -Protocol TCP -Action Allow -Enabled True