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:
- Open Command Prompt Run –> cmd
- Run the following command:
pkgmgr /iu:”TelnetClient” - 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.
- Open PowerShell by going to Run –> powershell
- Run the following command
tnc google.com -port 80
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.
Обмен данными по локальной сети или через интернет осуществляется путем подключения друг к другу двух компьютеров. Чтобы получить данные с удаленного сервера, требуется соблюсти несколько условий – наличие IP-адреса у источника и получателя, выбор конкретного протокола приема-передачи и открытые порты на обоих компьютерах.
Что такое порт компьютера
Порт – это виртуальное дополнение к сетевому адресу, которое позволяет разделить запросы разных приложений и обрабатывать их автономно. Часть постоянно занята системными службами Windows или другой операционки, остальные свободны для использования прикладными программами, в том числе запускаемыми на удаленных серверах.
Особенности портов:
- Иногда порты путают с разъемами на материнской плате (формально они и являются ими, но там речь идет о подключении физических устройств).
- Общее количество портов составляет 65535. Они имеют определенное назначение, например, 20-21 «по умолчанию» используется для соединения по FTP, а 110 выделен под почтовый протокол POP3.
- Сочетание IP-адреса и порта принято называть сокетом или файловым дескриптором, при помощи которого программа передает данные.
Перед подключением к какому-либо порту рекомендуется проверить, свободен ли он. Если нет, то операционная система выдаст ошибку, и соединение прервется. Многие программы делают проверку в автоматическом режиме и сами пытаются менять номера в поиске незанятого подключения. Но в ряде случаев это требуется сделать вручную, например, при отладке собственного кода.
Комьюнити теперь в Телеграм
Подпишитесь и будьте в курсе последних IT-новостей
Подписаться
Как проверить, открыт ли порт для подключения
Порты присутствуют у всех сетевых устройств, включая маршрутизаторы и роутеры, поэтому при анализе среды важно понимать, какой именно узел проверяется. На этом отчасти основаны системы безопасности, когда ради блокировки вероятных хакерских атак закрываются все свободные сокеты и открываются только те, которые используются корпоративным софтом.
Существует три основных способа проверки открытых портов:
- Специализированные онлайн-сервисы.
- Прикладные приложения, запускаемые на компьютере.
- Встроенные в операционную систему утилиты.
Выбор решения зависит от задач. Так, если требуется открыть доступ к своему компьютеру извне, можно воспользоваться сервисами 2ip.ru или portscan.ru. При локальных работах удобнее приложения типа Portforward Network Utilities или штатная утилита TELNET. Она поставляется в «стандартной» сборке Windows и доступна для запуска в консоли CMD.
Перечень открытых портов на локальном компьютере
Открытый порт на домашнем или рабочем компьютере – это фактически «дыра» в безопасности и риски утраты контроля над ситуацией. Именно через них проникают трояны и иные вирусы, которые имеют цель предоставить злоумышленнику возможность удаленного подключения к ПК без разрешения владельца.
Проверить занятые порты легко:
- Нужно нажать комбинацию клавиш <Win+R>.
- Ввести команду CMD и нажать кнопку Enter.
- Ввести команду netstat –a и повторно нажать Enter.
В консоли отобразится перечень занятых портов с указанием, какое приложение или служба ими «распоряжается». Такой вариант проверки интересен тем, что он дает объективную картину. Если рассчитывать только на онлайн-сервисы, иногда создается впечатление, что открытых портов нет. Эффект создается из-за блокировки внешних запросов брандмауэром Windows или другим ПО.
Если хочется изучить список на предмет «посторонних» программ, его лучше выгрузить в файл при помощи команды netstat –a >имя.txt. По умолчанию список сохраняется в каталоге пользователя, в аккаунте которого происходил запуск утилиты (типа C:\\Пользователи\User\). При желании перед запуском утилиты можно перейти в корень диска командой cd c:\.
Просмотр открытых портов на удаленном компьютере
При взаимодействии с удаленным сервером используется другая утилита – TELNET. В Windows она по умолчанию отключена, потому что не относится к пользовательским приложениям. Перед первым запуском придется провести «активацию». Существует два способа включения – в консоли или через графический интерфейс.
Активация заключается во вводе специальной команды:
dism /online /Enable-Feature /FeatureName:TelnetClient
Она сработает только при запуске консоли с правами администратора. Схема открытия приложения несколько иная:
- Нажать комбинацию клавиш <Win+X>.
- Выбрать пункт «Командная строка (администратор)».
- В открывшемся окне ввести команду активации telnet.
Если пользователь предпочитает управлять компьютером через графический интерфейс, нужно запустить панель управления, а в ней утилиту «Удаление программы». В открывшемся окне нужно перейти в раздел «Включение или отключение компонентов Windows», далее в общем списке найти строку «Telnet», поставить в ней галочку и нажать кнопку ОК. Все, служба активирована и готова к использованию (даже в консоли).
Синтаксис:
telnet опции хост порт
Хост – это домен или его IP-адрес, порт – виртуальное дополнение для образования сокета, опции же позволяют менять режим подключения. Их основные варианты:
- -4 – использовать адреса стандарта IPV4;
- -6 – использовать адреса стандарта IPV6;
- -8 – применять 8-битную кодировку типа Unicode;
- -E – отключение поддержки Escape-последовательностей;
- -a – вход с именем пользователя из переменного окружения User;
- -b – использовать локальный сокет;
- -d – включить режим отладки;
- -p – режим эмуляции rlogin;
- -e – задать символ начала Escape-последовательности;
- -l – пользователь для авторизации на удаленном сервере.
Простейший вариант проверки открытых портов – это ввод команды без опций:
telnet 10.0.119.127 80
Если на экран будет выведено сообщение «Сбой подключения», порт закрыт, нужно подбирать другой номер. Если порт открыт, пользователь увидит пустой экран или приглашение со стороны сервера ввести логин и пароль.
In this tutorial, we will learn how to run the netstat
command to check open ports in Windows Operating System. We will also look at command options and how to use the findstr
command (similar to grep) to filter the netstat output.
To check open ports, open a command prompt (or PowerShell) as administrator and run the netstat
command as follows:
netstat -aon
The command displays lots of information. What you should pay attention to are Local Addresses that are in the LISTENING state.
As you can see in the previous screenshot, In my Windows 10 computer, port 22 (SSH) is open.
Administrators can run the following command to show opened ports only without all other details:
netstat -aon | findstr /i listening
One important point is that the Windows Firewall may block a port even if it is in the listening state. In the Windows Defender Firewall with Advanced Security, there has to be a corresponding inbound firewall rule to match the listening port (Anything with a green checkmark is an open rule).
The Foreign Address column of the output shows the IP address and port of the computer/server at the remote end of the connection.
To check that the port is open from a remote computer, an administrator can run the telnet
command from a remote computer against the IP address of the Windows computer.
For example, to check if port 22 is open, I will run the telnet
command from a remote computer as follows:
telnet IP_ADDRESS 22
Replace IP_ADDRESS with the actual IP Address of the Windows computer.
Filtering netstat using findstr
Administrators can use the findstr
CMD command (which is similar to grep
) to filter netstat
command data based on string patterns.
For example, run the following command to check TCP connections in TIME_WAIT
State.
netstat -a | findstr /i TIME_WAIT
The /I
option is for the case insensitive matching.
Command Options
Windows netstat command, without any command-line arguments, displays active TCP connections.
It also includes some useful command options to show network connections and ports in various forms, such as show connections and opened ports based on the protocol, find the process id of a connection/port, view network statics, and find the application that utilizes connections and ports.
-a | displays all network connections and ports on which Windows is listening (include both IPv4 or IPv6 addresses). |
-b | The output shows you which applications are using each active connection and ports (need administrative privileges). |
-e | Displays network statistics, such as the Errors, the number of bytes, and packets sent and received. |
-n | Displays addresses and ports in numerical format. |
-f | When used, the output will contain Fully Qualified Domain Names (FQDNs) of IP addresses, if available. |
-o | Displays an additional column that contains the Process ID (PID). |
-p | Display data for a specific protocol (e.g., -p TCP). The Protocol can be one of the following: TCP , UDP , TCPv6 , or UDPv6 . If combined with the -s option, Protocol can be TCP , UDP , ICMP , IP , TCPv6 , UDPv6 , ICMPv6 , or IPv6 . |
-r | Check Windows routing table. |
-s | Displays detailed network statistics for each protocol (IPv4 , IPv6 , ICMPv4 , ICMPv6 , TCP , and UDP ). |
interval | Sets Time interval (in seconds) to automatically update the output. See examples to learn more. |
Examples: Using the netstat command
List all Active TCP connections:
netstat
Check open ports:
netstat -aon | findstr /i listening
Only want to see information about TCP protocol:
netstat -a -p tcp
Show network statistics:
netstat -s
Real-time network monitoring — In the following example, we set a 5 second time interval to check active network connections in real-time. The number 5 causes the command to repeat every five seconds (Press CTRL+C
to quit).
netstat -n 5
If you need more information about the Windows netstat command, type netstat \?
in the command prompt.
- November 4, 2021
- Windows
I’m sure there were times when you had to check if a port is accessible from one computer to another. In the earlier days we used to test network connectivity to a specific port of the remote computer using telnet command. Telnet used to come preinstalled in Windows, but in latest Windows OS not anymore.
In these days some companies have restrictions on installing third party programs or new services including telnet on their machines. That’s why, in this tutorial we’ll see how can we achieve our goal only with what we have available, without installing anything else.
And what we have available is PowerShell and cmdlet Test-NetConnection . With the -Port parameter, the command will make a TCP three-way handshake on the specified port and report back if the connection succeeded or not.
Test-NetConnection <FQDN/IP Address> -Port <port number>
The Test-NetConnection command will provide you basic information about the network connection like computer name, IP address, Interface, source IP, whether the ping is successful or not, Ping reply time and finally TcpTestSucceeded. TcpTestSucceeded will report as True if the port is open and false if the port is closed. In the above picture you will see the result for both cases.
Conclusion: This PoweShell cmdlet will come in handy every time when you will have to troubleshoot a connection issue. For me it was very useful for a few times and I hope it will be the same for you.
Download Article
Test the status of a specific local or remote port
Download Article
Are you looking for a quick way to check if a port on your router or firewall is open? It’s actually pretty simple. The right way to do it just depends on whether you’re using a Mac or PC and what kind of port you’re checking. We’ll walk you through how to do it step-by-step on Windows and macOS.
Easy Ways to Identify Open Ports
- On Windows devices, enable Telnet. Open a command prompt and type “ipconfig.” Use the IP address and port number to locate an open port.
- For Mac devices, open a Terminal window. Type “netsat -nr | grep default” into the program. Then, type “nc -vs” + your IP + port number to locate.
- Check an External port by visiting https://canyouseeme.org/ and enter the port you want to check. Click “check port” to see if it’s open and available.
-
You can use Telnet to check if a certain port is open on your local router or access point. Here’s how to enable it:[1]
- Type windows features in to the search bar. If you don’t see the search bar, click the circle or magnifying glass to the right of the Start menu.
- Click Turn Windows features on or off.
- Check the box next to Telnet Client and click OK.
- Click Close when the app is finished installing.
-
Here’s how to open the command prompt:
- Type cmd into the Windows search bar.
- Click Command prompt in the search results.
Advertisement
-
This displays a bunch of network information.
-
The address that appears next to «Default Gateway» in the ipconfig results is the local address of your router.
-
This opens the Microsoft Telnet prompt.
-
For example, if you wanted to see if port 25 is open on your router, and your router’s IP address is 10.0.0.1, you would type open 10.0.0.1 25.
-
Telnet will try to connect to the port.
- If you see a message that says «Please press Enter» or «Press any key to continue,» the port is open.
- If you see a message that says «Could not open connection,» the port is not open.
Advertisement
-
To open a Terminal window, open Spotlight by clicking the magnifying glass at the top-right corner of the screen, type terminal, and then click Terminal in the search results.
- Use this method to see if a port is open on your local router or access point.
-
The router’s IP address appears next to «default» at the top of the results.
-
For example, if you wanted to see if port 25 is open on your router, and your router’s IP address is 10.0.0.1, you would type nc -vz 10.0.0.1 25.
-
Here’s how to interpret the results:
- If the port is open, you’ll see a message that says the connection succeeded.
- If the port is closed, you’ll see a message that says the connection was refused or timed out.
Advertisement
-
If the search bar is not already open, click the circle or magnifying glass to the right of the Start menu to open it.[2]
- Use this method if you want to see if Windows is set up to allow an app you’ve installed to communicate through your firewall.
- The Windows firewall is enabled by default. If you’ve installed your own firewall software, use that software to check if an app is allowed through.
-
This opens your Firewall and Network Protection settings.
-
It’s one of the text links near the bottom of the window. A list of apps allowed through the firewall will appear.
- If the app is allowed through the firewall only when you’re connected to a network you’ve marked as «private» (such as when you’re on your home network), a check will appear in the «Private» column next to the app.
- If the app is allowed through the firewall when you’re connected to a public network, a check will appear in the «Public» column.
-
If you don’t see the app on the «Allowed apps and features» list, click the Change Settings button at the top-right corner, and then follow these steps:[3]
- Click Allow another app near the bottom.
- Click Browse, select the app, and then click Open.
- Click Network Types near the bottom-left corner, select a privacy preference, and then click OK.
- Click Add to add the app, and then click OK.
Advertisement
-
Go to https://www.canyouseeme.org in a web browser. You can use it to see if a port on your computer or network is accessible on the internet. The website will automatically detect your IP address and display it in the «Your IP» box.[4]
- There are many different sites you can use to check for an open port. Search for «open port check tool» in your favorite search engine to find an alternative, if desired.[5]
- There are many different sites you can use to check for an open port. Search for «open port check tool» in your favorite search engine to find an alternative, if desired.[5]
-
Type the port you want to check (e.g., 22 for SSH) into the «Port to Check» box.[6]
-
If the port is open and available, you’ll see a confirmation message. If not, you’ll see a message that says «Error: I could not see your service on (your IP address) on port (the port number).»[7]
Advertisement
-
The Mac firewall is not enabled by default.[8]
-
It’s the house icon on the top row.
-
It’s near the top-center part of the window.
- If you see the message «Firewall:On» near the top of the tab, this means your firewall is active.
- If the firewall is not active but you want it to be, click the padlock icon at the bottom-left part of the window, enter your administrator password, and then click Turn On Firewall.
-
This opens your settings, including a list of apps and services set to either allow or disallow incoming connections.[9]
- If an app or service has a green dot and the text «Allow incoming connections,» that means its port is open.
- If you see a red dot that says «Block incoming connections,» the port is closed.
- You can toggle whether a port is allowed or not allowed by clicking the double-arrow icon next to the app’s current status, and choosing an option.
Advertisement
Add New Question
-
Question
How do I check if a port is open Windows 10?
Luigi Oppido is the Owner and Operator of Pleasure Point Computers in Santa Cruz, California. Luigi has over 25 years of experience in general computer repair, data recovery, virus removal, and upgrades. He is also the host of the Computer Man Show! broadcasted on KSQD covering central California for over two years.
Computer & Tech Specialist
Expert Answer
An easy way to do this is to go to canyouseeme.org and type in the port number into the webpage. It’ll be able to tell you whether or not the port is open.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 845,515 times.