Windows check port open remote

What is a simple way in Windows to test if traffic gets through to a specific port on a remote machine?

Stan Kurdziel's user avatar

asked Jul 2, 2009 at 18:01

Matt's user avatar

1

I found a hiddem gem the other day from Microsoft that is designed for testing ports:

Portqry.exe

«Portqry.exe is a command-line utility that you can use to help troubleshoot TCP/IP connectivity issues. Portqry.exe runs on Windows 2000-based computers, on Windows XP-based computers, and on Windows Server 2003-based computers. The utility reports the port status of TCP and UDP ports on a computer that you select. «

Steve Bennett's user avatar

answered Jul 2, 2009 at 18:30

Peter M's user avatar

Peter MPeter M

1,0369 silver badges20 bronze badges

3

Which version of Windows? For Windows 8/Server 2012 and later, the following works in PowerShell:

Test-NetConnection 128.159.1.1 -Port 80

Some Googling will also turn up alternatives which use the .NET Framework directly (since PowerShell lets you do that) for systems running lower versions of Windows that won’t have Test-NetConnection available.

If you’re not averse to using third-party utilities, Nmap is also a very good friend to have and it works from the command line.

answered Oct 16, 2014 at 6:18

Iszi's user avatar

IsziIszi

2,4068 gold badges26 silver badges33 bronze badges

6

Use the telnet command to connect to the server on the specified port, and see if a connection can be established.

Success:

$ telnet my_server 25
220 my_server ESMTP Postfix

Fail:

$ telnet my_server 23632
Connecting To my_server...Could not open connection to the host, on port 23632:
Connect failed

answered Jul 2, 2009 at 18:05

Jørn Schou-Rode's user avatar

Jørn Schou-RodeJørn Schou-Rode

7401 gold badge6 silver badges12 bronze badges

4

Telnet will work for TCP.

Netcat is a better tool for these sorts of things, including UDP, watch out though, some AV softwares consider it an ‘evil hacker tool’

answered Jul 2, 2009 at 18:07

whatsisname's user avatar

whatsisnamewhatsisname

2911 gold badge3 silver badges8 bronze badges

Use netcat Windows port:

>nc -zvv www.google.com 80
www.google.com [108.177.96.103] 80 (http) open
sent 0, rcvd 0
>

>nc -zvv www.google.com 888
www.google.com [108.177.96.147] 888 (?): TIMEDOUT
sent 0, rcvd 0: NOTSOCK
>

answered Oct 25, 2016 at 12:48

rustyx's user avatar

rustyxrustyx

1,6863 gold badges21 silver badges30 bronze badges

0

the following command will list all ports in use on the machine…

netstat -a

The output contains the protocol, local address, foreign address and current state

Netstat documentation on microsoft.com

answered Jul 11, 2012 at 13:05

Baldy's user avatar

BaldyBaldy

1952 silver badges11 bronze badges

1

As @iszi’s answer suggested, using the free nmap utility downloadable from nmap.org is a viable option. It could scan for UDP or TCP ports. Example:

nmap -n -P0 -p "80,443" microsoft.com duolingo.com

where

-n           never do DNS resolution
-P0          do not ping to test 'up' state
-p           this is the list of desired ports
"22,80,443"  check in SSH, HTTP and HTTPS in TCP

The port list should be inside quotes in Windows because the comma is interpreted as space in the shell.

Result:

Nmap scan report for microsoft.com (20.53.203.50)
Host is up (0.21s latency).
Other addresses for microsoft.com (not scanned): 20.81.111.85 20.103.85.33 20.84.181.62 20.112.52.29

PORT    STATE SERVICE
80/tcp  open  http
443/tcp open  https

Nmap scan report for duolingo.com (184.72.124.184)
Host is up (0.068s latency).

PORT    STATE SERVICE
80/tcp  open  http
443/tcp open  https

Nmap done: 2 IP addresses (2 hosts up) scanned in 0.62 seconds

Port 22 is not open on the tested hosts.

Reference: https://nmap.org/book/man.html

answered Oct 27, 2022 at 23:16

Fjor's user avatar

FjorFjor

1965 bronze badges

‘netstat’ is you friend.

answered Jul 2, 2009 at 18:03

quosoo's user avatar

2

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

If you’re checking from the outside, not from the server itself, and you don’t want to bother installing telnet (as it doesn’t come with the last versions of Windows) or any other software, then you have native PowerShell:

Test-NetConnection -Port 800 -ComputerName 192.168.0.1 -InformationLevel Detailed

(Unfortunately this only works with PowerShell 4.0 or newer. To check your PowerShell version, type $PSVersionTable.)

PS: Note, these days there are some claims on the twittersphere that hint that this answer could be improved by mentioning «Test-Connection» from PowerShell Core, or the shortcut «tnc». See https://twitter.com/david_obrien/status/1214082339203993600 and help me edit this answer to improve it please!


(If you have a PSVersion < 4.0, you’re out of luck. Check this table:

Enter image description here

Even though you can upgrade your version of PowerShell by installing the Windows Management Framework 4.0, it didn’t do the trick for me, Test-NetConnection cmdlet is still not available).

Обмен данными по локальной сети или через интернет осуществляется путем подключения друг к другу двух компьютеров. Чтобы получить данные с удаленного сервера, требуется соблюсти несколько условий – наличие IP-адреса у источника и получателя, выбор конкретного протокола приема-передачи и открытые порты на обоих компьютерах.

Что такое порт компьютера

Порт – это виртуальное дополнение к сетевому адресу, которое позволяет разделить запросы разных приложений и обрабатывать их автономно. Часть постоянно занята системными службами Windows или другой операционки, остальные свободны для использования прикладными программами, в том числе запускаемыми на удаленных серверах.

Проверка порта на доступность

Особенности портов:

  1. Иногда порты путают с разъемами на материнской плате (формально они и являются ими, но там речь идет о подключении физических устройств).
  2. Общее количество портов составляет 65535. Они имеют определенное назначение, например, 20-21 «по умолчанию» используется для соединения по FTP, а 110 выделен под почтовый протокол POP3.
  3. Сочетание IP-адреса и порта принято называть сокетом или файловым дескриптором, при помощи которого программа передает данные.

Перед подключением к какому-либо порту рекомендуется проверить, свободен ли он. Если нет, то операционная система выдаст ошибку, и соединение прервется. Многие программы делают проверку в автоматическом режиме и сами пытаются менять номера в поиске незанятого подключения. Но в ряде случаев это требуется сделать вручную, например, при отладке собственного кода.

Комьюнити теперь в Телеграм

Подпишитесь и будьте в курсе последних IT-новостей

Подписаться

Как проверить, открыт ли порт для подключения

Порты присутствуют у всех сетевых устройств, включая маршрутизаторы и роутеры, поэтому при анализе среды важно понимать, какой именно узел проверяется. На этом отчасти основаны системы безопасности, когда ради блокировки вероятных хакерских атак закрываются все свободные сокеты и открываются только те, которые используются корпоративным софтом.

Открыт ли порт

Существует три основных способа проверки открытых портов:

  1. Специализированные онлайн-сервисы.
  2. Прикладные приложения, запускаемые на компьютере.
  3. Встроенные в операционную систему утилиты.

Выбор решения зависит от задач. Так, если требуется открыть доступ к своему компьютеру извне, можно воспользоваться сервисами 2ip.ru или portscan.ru. При локальных работах удобнее приложения типа Portforward Network Utilities или штатная утилита TELNET. Она поставляется в «стандартной» сборке Windows и доступна для запуска в консоли CMD.

Перечень открытых портов на локальном компьютере

Открытый порт на домашнем или рабочем компьютере – это фактически «дыра» в безопасности и риски утраты контроля над ситуацией. Именно через них проникают трояны и иные вирусы, которые имеют цель предоставить злоумышленнику возможность удаленного подключения к ПК без разрешения владельца. 

Командная строка

Проверить занятые порты легко:

  1. Нужно нажать комбинацию клавиш <Win+R>.
  2. Ввести команду CMD и нажать кнопку Enter.
  3. Ввести команду netstat –a и повторно нажать Enter.

В консоли отобразится перечень занятых портов с указанием, какое приложение или служба ими «распоряжается». Такой вариант проверки интересен тем, что он дает объективную картину. Если рассчитывать только на онлайн-сервисы, иногда создается впечатление, что открытых портов нет. Эффект создается из-за блокировки внешних запросов брандмауэром Windows или другим ПО.

Порт телнет

Если хочется изучить список на предмет «посторонних» программ, его лучше выгрузить в файл при помощи команды netstat –a >имя.txt. По умолчанию список сохраняется в каталоге пользователя, в аккаунте которого происходил запуск утилиты (типа C:\\Пользователи\User\). При желании перед запуском утилиты можно перейти в корень диска командой cd c:\.

VDS Timeweb арендовать

Просмотр открытых портов на удаленном компьютере

При взаимодействии с удаленным сервером используется другая утилита – TELNET. В Windows она по умолчанию отключена, потому что не относится к пользовательским приложениям. Перед первым запуском придется провести «активацию». Существует два способа включения – в консоли или через графический интерфейс.

Запуск утилиты telnet

Активация заключается во вводе специальной команды:

dism /online /Enable-Feature /FeatureName:TelnetClient

Она сработает только при запуске консоли с правами администратора. Схема открытия приложения несколько иная:

  1. Нажать комбинацию клавиш <Win+X>.
  2. Выбрать пункт «Командная строка (администратор)».
  3. В открывшемся окне ввести команду активации telnet.

Команда telnet

Если пользователь предпочитает управлять компьютером через графический интерфейс, нужно запустить панель управления, а в ней утилиту «Удаление программы». В открывшемся окне нужно перейти в раздел «Включение или отключение компонентов Windows», далее в общем списке найти строку «Telnet», поставить в ней галочку и нажать кнопку ОК. Все, служба активирована и готова к использованию (даже в консоли).

клиент Телнет

Синтаксис:

telnet опции хост порт

Хост – это домен или его IP-адрес, порт – виртуальное дополнение для образования сокета, опции же позволяют менять режим подключения. Их основные варианты:

  1. -4 – использовать адреса стандарта IPV4;
  2. -6 – использовать адреса стандарта IPV6;
  3. -8 – применять 8-битную кодировку типа Unicode;
  4. -E – отключение поддержки Escape-последовательностей;
  5. -a – вход с именем пользователя из переменного окружения User;
  6. -b – использовать локальный сокет;
  7. -d – включить режим отладки;
  8. -p – режим эмуляции rlogin;
  9. -e – задать символ начала Escape-последовательности;
  10. -l – пользователь для авторизации на удаленном сервере.

Простейший вариант проверки открытых портов – это ввод команды без опций:

telnet 10.0.119.127 80

Если на экран будет выведено сообщение «Сбой подключения», порт закрыт, нужно подбирать другой номер. Если порт открыт, пользователь увидит пустой экран или приглашение со стороны сервера ввести логин и пароль.

There were times when we used to test network connectivity of a specific port of the router using telnet command. Telnet used to come pre-installed in Windows but not in Windows 10. We explore different possibilities to check if a remote network port is open using command line options in Windows 10.

Windows 10 does not come with Telnet pre-installed. Even DOS Command Prompt has also become secondary with PowerShell taking the center stage.

Portqry used to be the command of choice for checking remote ports being alive and listening but it was only available up till Windows XP and Windows Server 2003.

Install Telnet in Windows 10

If you are going strictly with a DOS based command then you are left with no option but to install telnet in Windows 10. To install Telnet, follow the instructions below:

  1. Open Command Prompt Run –> cmd
  2. Run the following command:
    pkgmgr /iu:”TelnetClient”
  3. Go to Run –> telnet

Check whether the port is open or not using Command Prompt

To check the network port, follow the instructions below:

Open Telnet using the three steps described above and issue the following command:

open google.com 80

Where google.com is the host you want to test. You can also put an IP address instead of the name. 80 is the port number which you want to probe. You should replace 80 with you desired port number.

If you receive “Press any key to continue” prompt, this means that the port is open and responding to telnet. If you receive “Could not open connection” or a blank screen with blinking cursor, this means the port is closed.

If you receive “Connection to host lost“, this means that the port is open but the host is not accepting new connections.

Check open port using PowerShell

Since Microsoft is pushing PowerShell and CMD has become a legacy system, we should be using PowerShell for most of our working. Let’s check whether a remote network port is open and listening or not.

  1. Open PowerShell by going to Run –> powershell
  2. Run the following command
    tnc google.com -port 80

Checking open port using PowerShell

Checking open port using PowerShell

tns is short for Test-NetworkConnection command. google.com is the host name. You can also put an IP address instead of the host name. You can specify the port number using the -port switch at the end of tnc command.

The TNC command will give you basic information about the network connection like computer name, IP address, Interface through which you are connecting, source IP, whether the ping is successful or not, Ping reply time and finally TcpTestSucceeded. TcpTestSucceeded will give you True if the port is open and false if the port is closed.

These commands and techniques are very useful when you are troubleshooting a network. Please let us know if this has been useful for you in the comments below and we will add more troubleshooting techniques in future.

In Windows 10, there is an ability to check the connection to a certain port on a remote machine. This is possible thanks to PowerShell. So, no third party tools are required and you can do it natively.

PowerShell is an advanced form of command prompt. It is extended with a huge set of ready-to-use cmdlets and comes with the ability to use .NET framework/C# in various scenarios. If you have the skill to write scripts, you can create some very powerful ones to automate Windows.

One of its cmdlets, Test-NetConnection, can be used to check the connection to a remote address and to a custom port specified by the user.

It has the following syntax:

Test-NetConnection -ComputerName COMPUTER_NAME -Port PORT_NUMBER

Use it as follows.

Test remote network port connection in Windows 10

  1. Open PowerShell
  2. Type the following command:
    Test-NetConnection -ComputerName COMPUTER_NAME -Port PORT_NUMBER

    Replace the COMPUTER_NAME portion with the actual remote PC name or IP address. Specify the port you need to connect to instead of the PORT_NUMBER portion.

For example, let’s test the connection to the DNS port (53) of the public Google DNS server (8.8.8.8). The command will look as follows:

Test-NetConnection -ComputerName 8.8.8.8 -Port 53

The output:windows-10-test-network-port-connectionThe line TcpTestSucceeded: True indicates that the connection was successful and the port 53 is open.

If you try to connect to some random port, which is closed for incoming connections, the Test-NetConnection cmdlet will respond with the following information:

windows-10-network-port-connection-failedThe output indicates that the connection has failed. The line TcpTestSucceeded has the value «False», but the cmdlet shows additional information that the target server is alive. It pinged the destination address and includes the results in the output. See the lines:

PingSucceeded          : True
PingReplyDetails (RTT) : 48 ms

For some servers, you may face the situation where PingSucceeded is False but TcpTestSucceeded is True. It just means that ICMP Ping is disabled on the target server but the destination port is open for incoming connections.

The cmdlet Test-NetConnection is one of the most useful PowerShell cmdlets. It saves your time and extends the built-in network diagnostics functionality in Windows 10.

The Test-NetConnection cmdlet is available in Windows 8.1 too.

That’s it.

Support us

Winaero greatly relies on your support. You can help the site keep bringing you interesting and useful content and software by using these options:

If you like this article, please share it using the buttons below. It won’t take a lot from you, but it will help us grow. Thanks for your support!

  • Windows cmd delete folder with files
  • Windows cmd show files in directory
  • Windows check port is busy
  • Windows cannot verify the digital signature for this file driver
  • Windows check disk on boot