Во всех версиях Windows вы можете настроить перенаправление/проброс сетевых портов (порт форвардинг) без использования сторонних инструментов. С помощью правила форвардинга вы можете перенаправить входящее TCP соединение (IPv4 или IPv6) с локального TCP порта на любой другой номер порта или даже на порт удаленного компьютера. Перенаправление портов в Windows чаще всего используется для обхода файерволов или чтобы спрятать сервер или службу от внешней сети (NAT/PAT).
В Linux можно довольно просто настроить перенаправление портов довольно просто с помощью правил iptables или firewalld. На серверных системах Windows Server для настройки перенаправления портов можно использовать службу маршрутизации и удаленного доступа (RRAS). Однако есть более простой способ настройки проброса портов с помощью режима
portproxy
в
netsh
, который одинаково хорошо работает в любой версии Windows (начиная с Windows XP и заканчивая современными Windows 11 и Windows Server 2022).
Содержание:
- Включить перенаправления порта в Windows с помощью netsh portproxy
- Настройка правил файервола для режима перенаправления портов Windows
- Управление правилами проброса портов netsh в Windows
- Настройка перенаправления портов с помощью NAT на Hyper-V Server
Включить перенаправления порта в Windows с помощью netsh portproxy
Вы можете включить и настроить перенаправление портов в Windows из командой строки через режим Portproxy команды Netsh.
Синтаксис команды следующий:
netsh interface portproxy add v4tov4 listenaddress=localaddress listenport=localport connectaddress=destaddress connectport=destport
где,
- listenaddress – локальный IP адрес, на котором ожидается соединение (полезно, если у вас несколько сетевых карт в разных подсетях/VLAN или несколько IP адресов на одном интерфейсе);
- listenport – номер локального TCP порта, подключение к которому будет перенаправляться (на этом порту ожидается входящее соединение);
- connectaddress – локальный или удаленный IP-адрес или DNS-имя хоста, на который нужно перенаправить сетевое подключение;
- connectport – номер TCP порта, на который нужно перенаправить трафик с порта listenport.
С помощью опций
netsh interface portproxy add
v4tov6
/
v6tov4
/
v6tov6
можно создавать правила порт форвардинга между для IPv4 и IPv6 адресов илимежду ними.
Допустим наша задача, заставить службу RDP отвечать на нестандартном порту, например 3340 (этот порт, конечно, можно изменить в настройках самой службы, но мы используем именно RDP для упрощения демонстрации техники перенаправления и проброса портов). Для этого нам нужно перенаправить входящий трафик на TCP порт 3340 на другой локальный порт – 3389 (это номер стандартного порта RDP).
Примечание. Обратите внимание, что номер локального порта, который вы указали в listenport не должен быть занят (слушаться) другой службой. Проверьте, что номер порта свободен командой:
netstat -na|find "3340"
Либо вы можете проверить что порт не слушается локально с помощью PowerShell командлета Test-NetConnection:
Test-NetConnection -ComputerName localhost -Port 3340
Чтобы создать правило перенаправления порта, запустите командную строку с правами администратора и выполните команду:
netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.10.1.110 connectport=3389 connectaddress=10.10.1.110
Где 10.10.1.110 – IP адрес вашего компьютера, на котором настраивается порт-форвардинг.
Теперь с помощью утилиты netstat проверьте, что в Windows теперь слушается локальный порт 3340:
netstat -ano | findstr :3340
Примечание. Если эта команда ничего не возвращает и перенаправление портов через netsh interface portproxy не работает, проверьте, что у вас в Windows включена служба iphlpsvc (IP Helper / Вспомогательная служба IP).
Проверьте состояние службу в консоли services.msc или с помощью команды PowerShell:
Get-Service iphlpsvc
Также на сетевом интерфейсе, для которого создается правило перенаправления портов должна быть включена поддержка протокола IPv6.
Это обязательные условия для корректной работы порт-форвардинга. Без службы IP Helper и без включенной поддержки IPv6 механизм перенаправления не работает.
В Windows Server 2003 / XP для работы перенаправления дополнительно нужно включить параметр реестра IPEnableRouter = 1 в ветке HKEY_LOCAL_MACHINE\ System\CurrentControlSet\services\Tcpip\Parameter. Можно включить этот параметр реестра с помощью PowerShell:
Set-ItemProperty -Path HKLM:\system\CurrentControlSet\services\Tcpip\Parameters -Name IpEnableRouter -Value 1
Этот параметр также позволяет включить маршрутизацию между разными подсетями в Hyper-V.
Вы можете определить процесс, который слушает указанный локальный порт по его PID (в нашем примере PID – 636):
tasklist | findstr 636
Теперь попробуйте подключиться на новый порт с удаленного компьютера при помощи любого RDP клиента. В качестве rdp-порта нужно указать 3340 (номер порта указывается после двоеточия после адреса rdp-сервера). Hапример, ,
10.10.1.110:3340
В этом примере порт 3340 нужно предварительно открыть в Windows Defender Firewall (см. следующий раздел статьи).
RDP подключение должно успешно установиться.
Правила проброса портов portproxy являются постоянными и не удаляются при перезагрузке Windows. Эти правила хранятся в реестре. Можно вывести список правил перенаправления netsh в реестре с помощью PowerShell:
Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\PortProxy\v4tov4\tcp
Если нужно перенаправить входящее TCP соединение на удаленный компьютер, используйте такую команду:
netsh interface portproxy add v4tov4 listenport=3389 listenaddress=0.0.0.0 connectport=3389 connectaddress=192.168.1.100
Это правило перенаправит весь входящий RDP трафик (с локального порта TCP 3389) с этого компьютера на удаленный компьютер с IP-адресом 192.168.1.100.
Нужно отметить, что режим portproxy в Windows не поддерживает сохранения IP источника в перенаправленном сетевом пакете. Т.е. если вы пробросите 443 порт Windows компьютера на внутренний веб-сервер, то на целевом сервере все входящие соединения будут идти с одного и того же IP адреса (Windows компьютер с активным режимом netsh portproxy). Если вам нужно использовать переадресацию с сохранением IP источника, нужно использовать NAT на внешнем фаейволе или на Hyper-V (описано ниже).
Так же для проброса локального порта на удаленный сервер в Windows можно использовать технику SSH туннелей.
Настройка правил файервола для режима перенаправления портов Windows
Проверьте, что в настройках вашего файервола (брандмауэра Windows или стороннего межсетевого экрана, такие часто включаются в состав антивирусного ПО) разрешены входящие подключения на новый порт. Вы можете добавить новое разрешающее правило в Windows Defender Firewall командой:
netsh advfirewall firewall add rule name=”RDP_3340” protocol=TCP dir=in localip=10.10.1.110 localport=3340 action=allow
Или с помощью командлета PowerShell New-NetFirewallRule:
New-NetFirewallRule -DisplayName "RDP_3340" -Direction Inbound -Protocol TCP –LocalPort 3340 -Action Allow -Enabled True
При создании входящего правила файервола для порта 3340 через графический интерфейс Windows Defender, не нужно ассоциировать с правилом программу или процесс. Данный порт слушается исключительно сетевым драйвером.
Если вы отключаете правило portproxy, не забудьте удалить оставшиеся правила файервола так:
netsh advfirewall firewall del rule name="RDP_3340"
или с помощью PowerShell:
Remove-NetFirewallRule -Name RDP_3340
Управление правилами проброса портов netsh в Windows
Можно создать любое количество правил перенаправления локальных портов Windows. Все правила netsh interface portproxy являются постоянными и сохраняются в системе после перезагрузки Windows.
Несколько раз сталкивался со случаями, когда в Windows Server 2012 R2 правила перенаправления портов сбрасывались после перезагрузки сервера. В этом случае рекомендуется проверить нет ли периодических отключений на сетевом интерфейсе, и не меняется ли IP адрес при загрузке ОС (лучше использоваться статический IP, вместо динамического DHCP). В качестве обходного решения пришлось добавить в планировщик Windows скрипт с правилами
netsh interface portproxy
, который создает правило перенаправления порта при загрузке операционной системы.
Чтобы вывести на экран список всех активных правил перенаправления TCP портов в Windows, выполните команду:
netsh interface portproxy show all
В нашем случае присутствует только одно правило форвардинга с локального порта 3340 на 3389:
Listen on ipv4: Connect to ipv4: Address Port Address Port --------------- ---------- --------------- ---------- 10.10.1.110 3340 10.10.1.110 3389
Совет. Также вы можете вывести вес правила перенаправления портов в режиме portproxy так:
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
Если вам нужно изменить настройки имеющегося правила portproxy, используйте такую команду:
netsh interface portproxy set v4tov4 listenport=3340 listenaddress=10.10.1.110 connectport=3300 connectaddress=10.10.1.110
В этом примере мы изменили адрес целевого порта portproxy на 3300.
Чтобы удалить определенное правило перенаправления порта, выполните:
netsh interface portproxy delete v4tov4 listenport=3340 listenaddress=10.10.1.110
Чтобы удалить все имеющиеся правила перенаправления и полностью очистить таблицу с правилами порт-форвардинга:
netsh interface portproxy reset
Важно. Такая схема перенаправления работает только для TCP портов. Трафик по UDP портам нельзя перенаправить с помощью режима portproxy. Также нельзя использовать в качестве connectaddress адрес localhost 127.0.0.1.
Если вы хотите включить перенаправление UDP трафика, можно использовать Windows Server с ролью RRAS и NAT. Вы можете настроить перенаправление портов между интерфейсами компьютера с помощью графической оснастки (
rrasmgmt.msc
) или командой:
netsh routing ip nat add portmapping Ethernet udp 0.0.0.0 53 192.168.1.54 53
Список NAT правил перенаправления портов в Windows Server можно вывести так:
netsh routing ip nat show interface
Если у вас на компьютере развернут WSL (Windows Subsystem for Linux), вы можете создать простой PowerShell скрипт создания правила перенаправления порта внутрь виртуальной машины WSL 2 (у ВМ на WSL 2 есть собственный виртуальный адаптер ethernet с уникальным IP адресом):
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;
Еще одной неявной возможностью portproxy является возможность создать видимость локальной работы любого удаленного сетевого сервиса. Например, вы хотите перенаправить весь трафик с локального порта 9090 на
google.com:443
netsh interface portproxy add v4tov4 listenport=9090 listenaddress=127.0.0.1 connectaddress=142.250.74.46 connectport=443 protocol=tcp
Теперь, если в браузере перейди по адресу https://localhost:9090 (нужно игнорировать ошибки SSL_ERROR_BAD_CERT_DOMAIN), откроется поисковая страница Google. Т.е. несмотря на то, что браузер обращается к локальному компьютеру, в нем открывается страница с внешнего веб-сервера.
Перенаправление портов также можно использовать, чтобы пробросить порт с внешнего IP адреса сетевой карты на порт виртуальной машины, запущенной на этом же компьютере. В Hyper-V такой проброс порта можно настроить на виртуальном коммутатор (см. ниже).
Windows не умеет пробрасывать диапазон TCP портов. Если вам нужно пробросить несколько портов, придется вручную создавать несколько правил перенаправления.
Настройка перенаправления портов с помощью NAT на Hyper-V Server
При использовании на вашем компьютере роли Hyper-V (может быть установлена как на Windows 10/11, так и на Windows Server или в виде бесплатного Windows Hyper-V Server), вы можете настроит проброс портов DNAT с помощью PowerShell. Допустим, вы хотите перенаправить все https запросы, которые получает ваш хост Hyper-V на IP адрес запущенной на хосте виртуальной машины. Для этого используется команды Hyper-V StaticMapping.
Создайте виртуальный коммутатор Hyper-V:
New-VMSwitch -SwitchName «NAT_Switch» -SwitchType Internal
Задайте IP адрес для нового виртуального коммутатора:
New-NetIPAddress -IPAddress 192.168.10.1 -PrefixLength 24 -InterfaceAlias "vEthernet (NAT_Switch)"
Включите NAT для данной сети:
New-NetNat -Name NATNetwork -InternalIPInterfaceAddressPrefix 192.168.10.0/24
Подключите ВМ в ваш коммутатор NAT_Switch и задайте для нее статический IP адрес (например, 192.168.10.80). В качестве шлюза-по умолчанию нужно указать IP адрес виртуального коммутатора Hyper-V (192.168.10.1).
Теперь можно настроить перенаправление порта с хоста Hyper-V в виртуальную машину:
Add-NetNatStaticMapping -NatName NATNetwork443 -Protocol TCP -ExternalIPAddress 0.0.0.0/24 -ExternalPort 443 -InternalIPAddress 192.168.10.80 -InternalPort 443
После выполнения этих команд весь HTTPS трафик, который приходит на порт TCP/443 гипервизора будет переправлен на серый IP адрес виртуальной машины.
Если вы хотите перенаправить нестандартный порт, не забудьте открыть его в Windows Firewall:
New-NetFirewallRule -DisplayName "HyperV_Nat_443" -Direction Inbound -LocalPort 443 -Protocol TCP -Action Allow -Enabled True
Полный список правил NAT на хосте Hyper-V можно вывести так:
Get-NetNat
You can configure network port forwarding in all Windows versions without using third-party tools. Using a port 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. Windows port forwarding is most commonly used to bypass firewalls or to hide an internal host or service from the external network (NAT/PAT).
In the Linux world, port forwarding is configured quite simply using iptables or firewalldrules. On Windows Server hosts, the Routing and Remote Access Service (RRAS) is typically used to configure port redirections. However, there is an easier way to enable port forwarding using netsh portproxy
mode, which works on all versions of Windows from Win XP to current builds of Windows 11 and Windows Server 2022.
Contents:
- How to Enable Port Forwarding on Windows with Netsh Portproxy?
- Configuring Firewall Rules for Port Forwarding Mode in Windows
- Managing Netsh Port Forwarding Rules in Windows
- Port Forwarding with NAT Rules on Hyper-V Virtual Switch
How to Enable Port Forwarding on Windows with Netsh Portproxy?
You can configure port forwarding in Windows using 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
- listenaddress –is a local IP address to listen for incoming connection (useful if you have multiple NICs in different subnets/VLANs or multiple IP addresses on one interface);
- listenport – a local TCP port number to listen on (the connection is waiting on);
- connectaddress – is a local or remote IP address (or DNS name) to which you want to redirect the incoming connection;
- connectport – is a TCP port to which the connection from
listenport
is forwarded to.
Using the netsh interface portproxy add
v4tov6
/v6tov4
/v6tov6
options, you can create port forwarding rules between IPv4 and IPv6 addresses.
Let’s suppose your task is to make the RDP service respond on a non-standard port, for example 3340 (of course, this port number can be changed in the Windows settings, but we are using RDP to make it easier to demonstrate the port forwarding technique). To do this, we need to redirect incoming traffic from TCP port 3340 to another local port 3389 (this is the default RDP port number).
Please note that the local port number that you specified in listenport should not be listened (used) by another service or process. Check that the port number is not used:
netstat -na|find "3340"
Alternatively, you can check that the port is not listening locally using the PowerShell cmdlet Test-NetConnection:
Test-NetConnection -ComputerName localhost -Port 3340
To create a port forwarding rule on Windows, open a command prompt as an administrator and run the following command:
netsh interface portproxy add v4tov4 listenport=3340 listenaddress=10.1.1.110 connectport=3389 connectaddress=10.1.1.110
Where 10.10.1.110 – the current IP address of your computer on which port forwarding is configured.
Now, use the netstat tool to check that Windows is now listening on local port 3340:
netstat -ano | findstr :3340
Note. If this command returns nothing and port forwarding through the netsh interface portproxy doesn’t work, make sure that you have the iphlpsvc (IP Helper) service running on your Windows device.
Check the status of the service in the services.msc
console or using the PowerShell command:
Get-Service iphlpsvc
IPv6 support must be enabled on the network interface for which the port forwarding rule is being created.
These are the prerequisites for the correct operation of port forwarding in Windows. Without the IP Helper service and without IPv6 support enabled, the port redirection won’t work.
To make port forwarding work on Windows Server 2003/XP, you must additionally set the IPEnableRouter parameter to 1 under the registry key HKEY_LOCAL_MACHINE\ System\CurrentControlSet\services\Tcpip\Parameter.
Set-ItemProperty -Path HKLM:\system\CurrentControlSet\services\Tcpip\Parameters -Name IpEnableRouter -Value 1
This option also allows you to enable routing between different subnets in Hyper-V.
You can identify the process that is listening on the specified port by its PID (in our example, the PID is 636):
tasklist | findstr 636
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 number. It is specified after the colon following the RDP host address. For example, 10.10.1.110:3340
In this example, port TCP/3340 must first be opened in Windows Defender Firewall (see the next section of the article).
The RDP connection should be established successfully.
Portproxy port forwarding rules are permanent and are not cleared when you restart Windows. These rules are stored in the registry. You can list the netsh forwarding rules in the registry using PowerShell:
Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\PortProxy\v4tov4\tcp
If you want to forward 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.100.101
This rule will redirect all incoming RDP traffic (from local TCP port 3389) from this computer to a remote host with an IP address 192.168.1.100.
Note that the portproxy mode in Windows doesn’t support saving the source IP in a forwarded network packet. Those, if you forward port 443 port from a Windows device to an internal web server, then all incoming connections will appear on the target server as coming from the same IP address (from your Windows host 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).
Also, you can use the SSH tunnels in Windows to forward the local port to a remote server.
Configuring Firewall Rules for Port Forwarding Mode in Windows
Ensure that your firewall (Microsoft Windows Defender or a third-party firewall, which is often part of the anti-virus software) allows 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="forwarded_RDPport_3340" protocol=TCP dir=in localip=10.1.1.110 localport=3340 action=allow
Or using the New-NetFirewallRule PowerShell cmdlet:
New-NetFirewallRule -DisplayName "forwarder_RDP_3340" -Direction Inbound -Protocol TCP –LocalPort 3340 -Action Allow
When creating an inbound firewall rule for TCP/3340 port via the Windows Defender Firewall graphical interface, you don’t need to associate a program or process with the rule. This port is only listened on by the network driver.
If you disable the portproxy rule, be sure to remove the remaining firewall rule as follows:
netsh advfirewall firewall del rule name="RDP_3340"
or remove the firewall rule with PowerShell:
Remove-NetFirewallRule -Name RDP_3340
Managing Netsh Port Forwarding Rules in Windows
You can create any number of port forwarding rules in Windows. All netsh interface portproxy rules are persistent and remain 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, you need to check whether there is a periodic disconnection on the network interface and whether the IP address changes when the OS boots (it is better to use a static IP instead of a dynamic DHCP). As a workaround, I had to add a batch script with the netsh interface portproxy rules to the Windows Task Scheduler that runs on the system startup.
To display a list of all enabled TCP port forwarding rules on 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 Address Port --------------- ---------- --------------- ---------- 10.1.1.110 3340 10.1.1.110 3389
Tip. You can also list all port forwarding rules in portproxy as follows:
netsh interface portproxy dump
#======================== # Port Proxy configuration #======================== pushd interface portproxy reset add v4tov4 listenport=3340 connectaddress=10.1.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 number to 3300.
To remove a specific port forwarding rule:
netsh interface portproxy delete v4tov4 listenport=3340 listenaddress=10.1.1.110
To remove all existing port mapping rules and completely clear the port forwarding rules table:
netsh interface portproxy reset
Important. This port forwarding scheme works only for TCP ports. You won’t be able to forward UDP ports this way. Also, you can’t use the loopback interface 127.0.0.1 (localhost) as the connectaddress
.
You can use Windows Server with the RRAS (Routing and Remote Access Service and NAT) role installed to enable port forwarding for UDP traffic. You can configure port forwarding between server network interfaces using the graphical snap-in (rrasmgmt.msc
) or with the command:
netsh routing ip nat add portmapping Ethernet1 udp 0.0.0.0 53 192.168.100.100 53
The list of NAT port forwarding rules in Windows Server can be listed as follows:
netsh routing ip nat show interface
If you have WSL (Windows Subsystem for Linux) installed on your computer, you can create a simple PowerShell script to create a port forwarding rule to the WSL 2 virtual machine (a WSL2 VM has its 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 make any remote network service look like it runs locally. For example, you want to forward the connections from local port 9090 to a remote HTTPS server (google.com:443
)
netsh interface portproxy add v4tov4 listenport=9090 connectport=443 connectaddress=google.com protocol=tcp
Now, the Google search page will open if you go to http://localhost:9090/ in your browser (you need to ignore SSL_ERROR_BAD_CERT_DOMAIN errors). So despite the browser accessing the local computer address, it opens a page from an external web server.
Windows cannot forward a range of TCP ports. If you need to forward multiple ports, you will have to manually create multiple portproxy redirecting rules.
Port forwarding rules can also be used to redirect a port from the external IP address of a physical NIC to a port of a virtual machine running on the same host. In Hyper-V, you can configure port forwarding on a Virtual Switch level (see below).
Port Forwarding with NAT Rules on Hyper-V Virtual Switch
When using the Hyper-V role on your computer (it can be installed on both Windows 10/11 and Windows Server, or as a free Hyper-V Server), you can configure DNAT port forwarding rules using PowerShell. Suppose you want to redirect all HTTPS traffic that your Hyper-V host receives to the IP address of the virtual machine running on the host. To do this, use 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.100.1 -PrefixLength 24 -InterfaceAlias "vEthernet (NAT_Switch)"
Enable NAT for this network:
New-NetNat -Name NATNetwork -InternalIPInterfaceAddressPrefix 192.168.100.0/24
Connect the VM to your NAT_Switch and assign it a static IP address (for example, 192.168.10.80). Set the Hyper-V virtual switch IP address (192.168.100.1 in this case) as the default gateway for the virtual machine’s network connection.
You can now enable 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 PowerShell commands, all HTTPS traffic that comes to the TCP/443 port of the Hyper-V host will be forwarded to the private IP address of the virtual machine.
If you want to create a port forwarding rule for a non-standard port, don’t forget to open it in Windows Firewall:
New-NetFirewallRule -DisplayName "HyperV_Nat_444" -Direction Inbound -LocalPort 444 -Protocol TCP -Action Allow -Enabled True
You can display a complete list of NAT/PAT port forwarding rules on a Hyper-V host like this:
Get-NetNat
Портмаппинг или переназначение портов — это процесс, позволяющий направить сетевой трафик с одного порта на другой, в том числе расположенный на другом интерфейсе. Данный функционал широко используется в маршрутизаторах для доступа из внешней сети к устройствам в локальной сети, находящейся за маршрутизатором. В Windows также можно реализовать портмаппинг, применяя встроенные функции фаервола или сторонние утилиты.
Приобрести оригинальные ключи активации Windows всегда можно у нас в каталоге от 1099 ₽
Настройка проброса портов через брандмауэр Windows
Несмотря на отсутствие явных настроек портмаппинга в интерфейсе брандмауэра Windows, такая возможность всё же существует — но она доступна только через командную строку и работает исключительно с протоколом TCP.
Синтаксис команды для портмаппинга выглядит следующим образом:
netsh interface portproxy add v4tov4 listenaddress=[ПРОСЛУШИВАЕМЫЙ_ЛОКАЛЬНЫЙ_АДРЕС] listenport=[ПРОСЛУШИВАЕМЫЙ_ЛОКАЛЬНЫЙ_ПОРТ] connectaddress=[АДРЕС_НАЗНАЧЕНИЯ] connectport=[ПОРТ_НАЗНАЧЕНИЯ]
Значение параметров команды:
— listenaddress — локальный адрес, с которого перенаправляется трафик.
— listenport — локальный порт, с которого перенаправляется трафик.
— connectaddress — адрес назначения для перенаправленного соединения.
— connectport — порт назначения для перенаправленного соединения.
Примеры:
Если у нас есть компьютер с адресом 10.0.0.13, и в сети с адресом 10.0.0.23 расположен веб-сервер, то для перенаправления запросов с порта 80 нашего компьютера на этот веб-сервер используем команду:
netsh interface portproxy add v4tov4 listenaddress=10.0.0.13 listenport=80 connectaddress=10.0.0.23 connectport=80
Для перенаправления подключения к RDP с нашего компьютера на другой, находящийся в сети, где сервер RDP слушает нестандартный порт 4200:
netsh interface portproxy add v4tov4 listenaddress=10.0.0.13 listenport=3389 connectaddress=10.0.0.23 connectport=4200
Чтобы просмотреть все настроенные правила переадресации, используйте команду:
netsh interface portproxy show all
Для удаления всех правил портмаппинга:
netsh interface portproxy reset
Проброс портов с помощью утилиты 3proxy
3proxy — это небольшая утилита, разработанная для перенаправления TCP и UDP трафика. Она также может выступать в роли различных прокси-серверов (HTTP, HTTPS, SOCKS и т.д.). Конфигурация проброса портов задается в файле 3proxy.cfg, который должен находиться в директории с утилитой.
Пример синтаксиса файла конфигурации:
[ПРОТОКОЛ TCP или UDP]pm -i[ПРОСЛУШИВАЕМЫЙ_ЛОКАЛЬНЫЙ_АДРЕС] [ПРОСЛУШИВАЕМЫЙ_ЛОКАЛЬНЫЙ_ПОРТ] [АДРЕС_НАЗНАЧЕНИЯ] [ПОРТ_НАЗНАЧЕНИЯ]
Например, чтобы перенаправить TCP трафик с локального адреса 10.0.0.13 и порта 80 на удаленный сервер с адресом 10.0.0.23 и портом 8080, используйте строку:
tcppm -i10.0.0.13 80 10.0.0.23 8080
Для перенаправления UDP порта 3389:
udppm -i10.0.0.13 3389 10.0.0.23 3389
Чтобы утилита начала работать как служба, добавьте параметр service в конфиг и запустите 3proxy.exe с параметром —install.
Проброс портов с помощью nginx
nginx — популярный веб-сервер, который также может использоваться для проброса портов и перенаправления трафика. В Windows существует версия nginx, позволяющая перенаправлять соединения, однако она не может работать как служба без дополнительного ПО.
Пример файла конфигурации для проброса порта 3390 на удаленный сервер с адресом 10.0.0.23 и портом 3389:
worker_processes 1;
events {
worker_connections 1024;
}stream {
upstream portforward {
server 10.0.0.23:3389;
}
server {
listen 3390;
proxy_pass portforward;
}
}
Для проброса UDP трафика потребуется указать udp в директиве listen:
server {
listen 3390 udp;
proxy_pass portforward;
proxy_responses 0;
}
Проброс портов в Windows может быть реализован разными способами, как с использованием встроенных средств (через командную строку и брандмауэр), так и с помощью сторонних утилит, таких как 3proxy или nginx. Выбор метода зависит от ваших потребностей и уровня сложности задачи. Все указанные инструменты позволяют настроить портмаппинг, чтобы обеспечить доступ к локальным ресурсам через внешний интерфейс.
Лицензионный ключ активации Windows от
Если для какой-то программы или игры требуется подключение через определенный порт, может оказаться что по умолчанию в системе этот порт закрыт и соединение не выполняется. При необходимости порты в Windows 11, Windows 10 и предыдущих версиях системы сравнительно легко открыть.
В этой инструкции подробно о том, как открыть порты в Windows 11 или Windows 10, посмотреть список открытых портов и дополнительная информация, которая может пригодиться, если при подключении всё равно возникают проблемы.
Открытие портов в брандмауэре Windows
Основной способ открытия портов в Windows 11 и 10 — настройка соответствующих правил в брандмауэре.
Прежде всего, откройте настройки Windows в режиме повышенной безопасности. Для этого можно использовать следующие способы:
Следующий шаг — настроить правила для нужных портов:
- Нажмите правой кнопкой мыши по «Правила для входящих подключений» и выберите пункт «Создать правило» в контекстном меню.
- В мастере создания правил выберите пункт «Для порта» и нажмите «Далее».
- Выберите тип протокола — TCP или UDP (если вам не известен нужный тип, уточните в справке по конкретной программе).
- Укажите порты: конкретный порт или их диапазон, можно использовать запятые для перечисления нескольких портов, или знак дефиса для указания их диапазона. Нажмите «Далее».
- Выберите пункт «Разрешить подключение».
- Укажите, для каких типов сетей (сетевых профилей) следует открыть порты.
- Укажите имя правила и, при желании, его описание. Затем нажмите кнопку «Готово».
- Выполните действия 1-7, но уже для исходящего подключения.
Готово, порт открыт и, если что-то ещё не мешает его работе, соединения должны будут устанавливаться.
Возможные проблемы и дополнительные необходимые действия
Если вы открыли требуемые порты в Windows, но несмотря на это соединение не устанавливается, следует учитывать, проверить или выполнить следующие действия:
- VPN может влиять не возможность обмена данными по определенным портам. Решение: отключить VPN, либо посмотреть, есть ли возможность открыть порты в ПО для VPN.
- Роутеры имеют собственные функции файрволла/брандмауэра и порты может потребоваться открыть (пробросить) и в настройках роутера. В зависимости от марки и модели Wi-Fi роутера, это выполняется в разных разделах: перенаправление портов (port forwarding), брандмауэр (firewall), межсетевой экран, виртуальные серверы. Логика настройки везде одна и та же: добавляются обычно совпадающие внешний порт и внутренний порт (нужный вам порт), указывается внутренний IP (локальный IP компьютера, к которому нужно пробросить порт), тип протокола — TCP или UDP, иногда требуется указать интерфейс, для соединений из «внешней сети» — WAN.
- Если само приложение заблокировано в брандмауэре, оно не сможет устанавливать соединения: можно добавить правила, разрешающие подключения для программы тем же способом, которым это выполнялось выше для портов.
- Наличие сторонних файрволлов и антивирусов с функциями защиты сети также может влиять на возможность установки соединений по определенным портам: следует проверить их настройки, при наличии такого ПО, чтобы открыть соответствующие порты или отключить защиту для них.
Как посмотреть открытые порты в Windows и какие программы их используют
В Windows постоянно открыты многие порты, требующиеся как для работы системных служб, программ (в том числе сторонних), браузеров. Вы можете посмотреть список открытых портов одним из следующих способов:
- Запустить командную строку и ввести команду (порты указаны после двоеточия в IP-адресе)
netstat -a
- Если требуется посмотреть, какие процессы используют определенные порты, используйте команду (требует запуска от имени администратора)
netstat -ab
- Для просмотра открытых портов с ИД (PID) процесса (по которому в диспетчере задач можно увидеть конкретный процесс):
netstat -aon
- Есть сторонние программы, позволяющие получить сведения об открытых портах и использующих их процессах, например, бесплатная NirSoft CurrPorts.
Список «стандартных» и наиболее часто используемых портов доступен в Википедии, но многие игры и программы могут использовать свои собственные, не указанные в списке порты для работы.
There are some games and applications that only work when you open a specific port. Without port forwarding, you won’t be able to receive or send the data needed for the proper running of those applications. This article helps you set up port forwarding on Windows 10.
We will explain what port forwarding is, giving a brief mention of the different types of port forwarding. The steps you should take to enable port forwarding such as setting up a static IP address will be explained. Finally, the method for opening firewall ports on Windows 10 will be explained.
What Is Port Forwarding? 🤔
Port forwarding or port mapping is basically the process involved in intercepting data headed for an IP address and redirecting them to a different IP address.
Usually, this redirection is caused by a program running on your computer, or by a change in settings on your computer. The port forwarding can also be caused by an intermediate hardware component such as a router or firewall.
Port Forwarding Explained
Normally, a router will note the header of an IP packet and send it to the appropriate interface which has already been linked, and this also sends the needed data to the information in the header.
Port forwarding however allows the intercepting application or device change to read the packet header, and after noting the destination, rewrites the header information and sends it to another computer.
The process of port forwarding makes services in a hidden internal network available to an external network. It does this by remapping or renaming the destination IP address and port number of the internal host. It is a good way of preserving public IP addresses. It hides servers and clients, protecting them from unwanted access.
It keeps all unwanted traffic off the network. All external communications by the network administrator on the internet are done using one IP address, while different servers with different IP addresses and ports do the task internally.
There are three types of port forwarding:-
- Local port forwarding
- Remote port forwarding
- Dynamic port forwarding
Local Port Forwarding:-
It allows a user to connect from your computer to another server. The firewalls that usually block those connections are bypassed. Data is forwarded using secure shells.
The data is redirected from a specific local port to a specified host using secure shells. This is the most common form of port forwarding.
Remote Port Forwarding:-
In remote port forwarding, the connections from a server to another remote network are done via secure shells. Two-port numbers as well as the address of the destination server must be known to use this form of port forwarding. This method allows other computers to access applications hosted on a remote server.
Dynamic Port Forwarding:-
It allows you to connect securely to a server you trust. This server acts as an intermediary for sending or receiving data on one or several destination servers.
Additional security is provided for users of untrusted networks. Also, dynamic port forwarding bypasses firewalls that restrict access to outside networks.
Steps Involved in Port Forwarding:-
For some programs—which need access to the internet—to function properly, certain ports that are not open by default need to be open. There are some important steps that need to be taken in order to ensure the kind of traffic you want to send or receive is gotten.
You need to give the device (your computer) a static IP address, so you won’t have to change the port forwarding settings every time you obtain a new IP address.
Additionally, you may need to use the router to set up a static IP address (this applies especially when you are receiving information on devices such as printers or game consoles). Next, you can locate the port forwarding option or open firewall ports on windows 10.
https://youtu.be/ZAbM0CnZzp4
How to Give Your Device a Static Ip Address
Having a static, rather than one that changes make it easier and convenient to do port forwarding on your computer. You would not need to continually change the port forwarding rules or settings on your Windows 10 anytime there is a change in the IP address.
There are some programs that would work better if you’ve assigned your computer a static IP address. Besides, if you need to use a specific port or range of ports, a static IP address makes your task easier. So, if for instance, you are running torrenting software, you should set up a static IP address.
You can set up this static IP address either from the settings on your computer or from the router.
To set up a static IP address on your Windows 10, you need to first identify the IP address you’re currently using.
Open the command prompt by using the keyboard shortcut “Windows Key + R” and typing cmd.
In the command prompt, type “ipconfig /all” and hit enter.
From the information output, copy the IPv4 address, subnet mask, default gateway and the DNS servers.
Note that there may be more than one IPv4 entry, hence, the one you should copy is the one under a heading such as “Ethernet adapter local area connection“, “Ethernet LAN adapter WiFi ” or “Ethernet adapter Ethernet”.
The IPv4 heading under headings for Bluetooth, VMware and other such headings should be ignored.
Once the required information has been copied or recorded, you are ready to set up a static IP address.
First, open a run dialog box. You can do this by pressing Windows key+ R. Enter ncpa.cpl and select ok. Doing this will open network connections.
The connection that has the same name as the one you identified in the command prompt should be right-clicked. You can either right-click it or tap and hold the connection. Next select ” properties” from the menu.
From the resulting list, choose Internet Protocol Version 4 (TCP/ IPv4), and then select properties, then select “use the following IP address“.
Enter all the details you copied from the from the command prompt and hit OK when you’ve done that.
Using the router to set up the static IP address is another option. You need to have the router’s IP address, username, and password. Once this information is in your possession, login to the router as admin.
Under the settings, find the client list (DHCP pool, or DHCP reservation). This shows you the name of all devices connected to the router as well as their respective IP addresses.
Reserve one of the IP addresses and assign it to your device so that it is always used when your device requests an IP address. You may need to choose the IP address from a list or add an IP address.
Once the IP address has been set to be static, you can also do all the settings for port forwarding. This can be done on your router.
If the settings done on the router still does not allow you to receive the information you desire, open firewall ports on your Windows computer.
To setup port forwarding, log in to the router as admin, then locate the port forwarding option.
This option may be found under “Network“, ” Wireless” or “Advanced” options under the settings. Also, note that the port forwarding option may have other names such as “Port Forwarding”, ” Port Triggering”, “Applications and Gaming” or “Port Range Forwarding”.
In the internal and external boxes, type the port number of the port you want to forward. Of you’re forwarding a range of ports, type the range in the start and end boxes.
Choose your desired protocol, either TCP or UDP, or both if needed. Most games indicate the ports that need to be open for it to function properly, as well as what protocol to use.
Once the protocol has been chosen, type your chosen static IP address. Finally, enable the port forwarding rule.
How to Open Firewall Ports on Windows 10
It is possible to manually allow a program access to the internet. You can open the firewall port needed. Most programs tell you what port needs to be open and what protocol is needed.
To open the firewall ports in Windows 10, navigate to the control panel, then to the system and security settings.
Then to windows firewall. Alternatively, you can search for firewall in the start menu.
Under windows firewall, select advanced settings on the left pane.
Right-click on “inbound rules” and click on “new rule“.
Next, click on the port radio button and hit next.
Add the protocol you want and the port number and select next.
In the next window, choose “allow the connection” and hit next.
Add the network type and click next. Finally, name the rule and click finish.
Conclusion
To fully use some applications and games, you need to do port forwarding on Windows 10. This opens up certain ports for information to be passed. The steps involved in port forwarding have been explained.
You can now enjoy access to whatever games and applications you need on your Windows 10.