Set up a Hyper-V Virtual Switch using a NAT Network
A couple of months ago I wrote a blog post about how you can create a new Hyper-V NAT Switch. Now this worked fine in some early Windows 10 builds, but Microsoft removed the parameter for the NAT Switch in some Windows 10 Insider builds. Today Sarah Cooley PM at the Microsoft Hyper-V team, documented how you can do this using newer Windows 10 builds.
- Windows 10 and Windows Server 2016 build 14295 or later
- Enabled Hyper-V role
- PowerShell, since this setting is not available in the UI right now
Create a new Hyper-V Virtual Switch
New-VMSwitch –SwitchName “NATSwitch” –SwitchType Internal
Configure the NAT Gateway IP Address
This configures the Virtual Network Adapter which was created while creating the Internal Virtual Hyper-V Switch.
New-NetIPAddress –IPAddress 172.21.21.1 -PrefixLength 24 -InterfaceAlias "vEthernet (NATSwitch)"
Now you can configure the NAT rule
New-NetNat –Name MyNATnetwork –InternalIPInterfaceAddressPrefix 172.21.21.0/24
After that you have finally created your NAT network and you can now use that network to connect your virtual machines and use IP Address from 172.21.21.2-172.21.21.254.
Create a new NAT forwarding
To forward specific ports from the Host to the guest VMs you can use the following commands.
This example creates a mapping between port 80 of the host to port 80 of a Virtual Machine with an IP address of 172.21.21.2.
Add-NetNatStaticMapping -NatName "VMSwitchNat" -Protocol TCP -ExternalIPAddress 0.0.0.0 -InternalIPAddress 172.21.21.2 -InternalPort 80 -ExternalPort 80
This example creates a mapping between port 82 of the Virtual Machine host to port 80 of a Virtual Machine with an IP address of 172.21.21.3.
Add-NetNatStaticMapping -NatName "VMSwitchNat" -Protocol TCP -ExternalIPAddress 0.0.0.0 -InternalIPAddress 172.16.0.3 -InternalPort 80 -ExternalPort 82
This also works with Windows and Hyper-V Containers.