Skip to content

Hyper-V NAT Static IP

Steps

  1. Open Powershell with Administrator Privilege
  2. Enter the following commands
ps1
New-VMSwitch -SwitchName "NAT" -SwitchType Internal
# This creates an vSwitch, you can see this using Win+R > enter ncpa.cpl > Enter

Get-NetAdapter
# This lists out all current internet adapter on your PC, find the one you just created
# It should be named like "vEthernet (NAT)", find its "ifIndex" and remember it

New-NetIPAddress -IPAddress 192.168.131.1 -PrefixLength 24 -InterfaceIndex $ifindex
# This is use for gateway creation, the -IPAddress will be your PC IP on this newly created NAT interface
# The -InterfaceIndex should be the number you remember in the previous command.

New-NetNat -Name NAT -InternalIPInterfaceAddressPrefix 192.168.131.0/24
# This command creates NAT network under subnet 192.168.131.0 with subnet mask 255.255.255.0

The IP address in the third and fourth command can be change to anything you like as long as the IP address is in C class(Local IP).

  1. After that, head over to Hyper-V manager, and open up your VM settings.
    Click on the network adapter section and change it to the NAT switch you created. Adapter Image

  2. Now connect to your VM, login to root account, and enter nmtui command Adapter Image

  3. Select Edit a connection

  4. Select eth0, press tab once, and then select <Edit...>, then hit Enter Adapter Image

  5. Don't edit profile name and device, use arrow down key to move cursor to IPv4 CONFIGURATION section

  6. Change <Automantic> to <Manual>

  7. Edit Addresses to 192.168.131.2/24

  8. Edit Gateway to 192.168.131.1

  9. DNS servers should be as same as your host system, in this case it's 192.168.1.1 and 168.95.1.1, if you would like more dns server on this vm you can select the <Add...> under the DNS servers section.

  10. Use arrow down to select <OK> to complete eth0 ip configuration. Adapter Image

  11. Press Esc to back to previous level, and select Activate a connection

  12. Select eth0, deactivate, then activate.

  13. Exit nmtui and try to ping internet, e.g. 1.1.1.1, 8.8.8.8, etc.

  14. If it shows host unreachable, restart VM.

  15. After that, repeat step 15, it should work now, connecting 192.168.56.2 from host system should show the page.

If you wish to expose your VM service to outside network, you'll need following PowerShell command(run as Administrator).

powershell
Add-NetNatStaticMapping -NatName "<NAT NAME>" -Protocol TCP -ExternalIPAddress 0.0.0.0/24 -ExternalPort <Port wish to expose> -InternalIPAddress <VM IP> -InternalPort <VM Service Port>