Home » Networking » Viewing and killing TCP IP connections Windows
Many time in troubleshooting or needing to view network traffic information or connection information, seeing your TCP/IP connections in Windows can provide valuable insight into problems or issues that may be going on in Windows with connectivity. Also, viewing connection information is a great way to narrow down on possible backdoor traffic to a workstation if malware is suspected. In this guide, we want to look at several tools and utilities to both view connection information as well as kill TCP connections in Windows that may be problematic or malicious.
Windows itself has many really nice tools built-in that will enable you to see TCP and UDP connections right out of the box via the commandline. Especially the later versions of Windows which include Powershell expand these capabilities as well.
Commandline Tools
Powershell
With powershell we have a whole new array of commandlets to peer inside of and control what is going on with Network connections in Windows. There are two commands in general among others that provide really powerful monitoring inside of Powershell and that is the get-nettcpconnection and get-udpendpoint. Take a look at the whole list of new powershell commands for monitoring and controlling TCP activity here: https://docs.microsoft.com
Get-NetTcpConnection – cmdlet gets current TCP connections. Use this cmdlet to view TCP connection properties such as local or remote IP address, local or remote port, and connection state.
Get-NetUDPEndpoint – gets current statistics for a UDP endpoint. The cmdlet returns UDP end point properties, such as local and remote UDP ports. If you do not specify any parameters, the cmdlet gets statistics for all UDP end points.
Netstat
Displays active TCP connections, ports on which the computer is listening, Ethernet statistics, the IP routing table, IPv4 statistics (for the IP, ICMP, TCP, and UDP protocols), and IPv6 statistics (for the IPv6, ICMPv6, TCP over IPv6, and UDP over IPv6 protocols). Used without parameters, netstat displays active TCP connections.
Below the command was issued netstat -ano
With the PID information you see above in the netstat output, you can use this number to correlate with PID information in Task Manager to identify the exact process and kill if need be.
wkillcx
Wkillcx is a small command-line utility to close any TCP connection under Windows XP/Vista/Seven as well as Windows Server 2003/2008. This is a great little commandline program that allows you to kill the remote IP:port connection information without knowing the PID. You simply issue the command, feed the appropriate connection information, it searches for that connection and kills it. Download wkillcx here: https://wkillcx.sourceforge.net/
syntax : wkillcx [dest_ip:dest_port] wkillcx 10.11.22.23:1234
GUI Tools
Along with the commandline tools included in Windows there are also a couple of really nice GUI tools that allow ones to see TCP activity as well as kill those TCP connections via killing the process that is spawning the TCP connections.
TCPView
TCPView is a Windows SysInternals Tool that is designed to basically show detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. The download of the utility also includes a commandline version of the tool in tcpvcon. Download TCPView here: https://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
Another really nice feature of TCPView is that you can right-click on any connection entry and then Kill the process that is using it:
Microsoft Message Analyzer 1.0
Microsoft Message Analyzer is a new tool for capturing, displaying, and analyzing protocol messaging traffic and other system messages. This is a relatively new tool that also can import data from the legacy Microsoft Network Protocol Analyzer 3.4.
This is a more full blown protocol analyzer, but can do many of the basic things we are referring too in the above guide. Download the Microsoft Message Analyzer here: https://docs.microsoft.com
Final Thoughts
Using the tools listed above, one can view network connection information via either the commandline or using GUI tools. This is extremely helpful when you are tracking down a rogue connection or a problematic process that has network hooks.
Brandon Lee is the Senior Writer, Engineer and owner at Virtualizationhowto.com, and a 7-time VMware vExpert, with over two decades of experience in Information Technology. Having worked for numerous Fortune 500 companies as well as in various industries, He has extensive experience in various IT segments and is a strong advocate for open source technologies. Brandon holds many industry certifications, loves the outdoors and spending time with family. Also, he goes through the effort of testing and troubleshooting issues, so you don’t have to.
2022-11-26
How do I kill a TCP connection in Windows?
Show activity on this post.
- open cmd. type in netstat -a -n -o. find TCP [the IP address]:[port number] ….
- CTRL+ALT+DELETE and choose “start task manager” Click on “Processes” tab.
- Now you can rerun the server on [the IP address]:[port number] without a problem.
How do you kill a TCP connection?
Use the DRop/-D command to terminate an individual TCP connection when you do not want to terminate the server itself, but want only to drop an individual connection with that server. Use the DROP/-D command to terminate old TCP connections if they prevent a server from being restarted.
How do I kill a port 8080 process?
Steps to kill process running on port 8080 in Windows cmd/terminal,
-
- #1 netstat -ano | findstr < Port Number >
- #2 taskkill /F /PID < Process Id >
How do I close a port on Windows?
This requires use of the dedicated Firewall app.
- Open the Windows Firewall app in Windows 10.
- Open advanced iFrewall settings.
- Click ‘Inbound Rules’ in the sidebar.
- Press ‘New Rule…’ in the right sidebar.
- Select the ‘Port’ rule type and press ‘Next’
- Choose your protocol.
- Enter the Windows 10 ports you want to open or close.
How do I close ports in Windows 10?
How do I block an established connection?
Simple Ban. In order to block established sessions the easy option is to adding a source rule in drop zone. This will add the source IP in PREROUTING_ZONES_SOURCE chain on mangle table. PREROUTING_ZONES_SOURCE is called in PREROUTING chain that handles all the traffic before any INPUT chain in filter or mangle.
How do I kill port 8080 in Windows?
Steps to kill process running on port 8080 in Windows,
- netstat -ano | findstr < Port Number >
- taskkill /F /PID < Process Id >
How do I stop a port 8080 from running in Command Prompt?
How do I stop a port from running in Command Prompt?
Windows
- Open a CMD window in Administrator mode by navigating to Start > Run > type cmd > right-click Command Prompt, then select Run as administrator.
- Use the netstat command lists all the active ports.
- To kill this process (the /f is force): taskkill /pid 18264 /f.
How do I stop a port running in Windows?
- Open Windows Terminal.
- Type the following command to show processes running on the port you’re looking to kill processes. netstat -ano | findstr :PORT.
- Type following to kill the process. kill PID.
What is Conntrack in Linux?
Connection tracking (“conntrack”) is a core feature of the Linux kernel’s networking stack. It allows the kernel to keep track of all logical network connections or flows, and thereby identify all of the packets which make up each flow so they can be handled consistently together.
How do I kill a running port?
How to kill the process currently using a port on localhost in…
- Run command-line as an Administrator. Then run the below mention command. netstat -ano | findstr : port number.
- Then you execute this command after identify the PID. taskkill /PID typeyourPIDhere /F.
Категории
Главная
-
-
Просмотров: 9881
Очень простой, но в то же время очень часто встречающийся вопрос, который вводит в ступор Windows-админов:
Как разорвать tcp/udp соединение в windows из командной строки?
ответ простой:
netsh advfirewall FIREWALL add rule name=»KMS» dir=in action=allow protocol=tcp localport=1688
или заюзать wipfw — всё это он умеет (аналог FreeBSD-фаервола ipfw)
Sometimes you have an application that keeps connections open while they should be closed.
Because Windows does not seem to have the capability to kill an connection without killing the whole process we’ll to use a 3rd party tool called cports.exe. Download here: https://www.nirsoft.net/utils/cports-x64.zip
$ProcessName= «BackgroundTransferHost»
$State = «CloseWait «
while ($true) {
sleep -Seconds 20
$id = (Get-Process $ProcessName).Id
Get—NetTCPConnection —OwningProcess $id —State $State | % {
.\cports.exe /close * * $_.RemoteAddress $_.RemotePort
}
}
Распознавание голоса и речи на C#
UnmanagedCoder 05.05.2025
Интеграция голосового управления в приложения на C# стала намного доступнее благодаря развитию специализированных библиотек и API. При этом многие разработчики до сих пор считают голосовое управление. . .
Реализация своих итераторов в C++
NullReferenced 05.05.2025
Итераторы в C++ — это абстракция, которая связывает весь экосистему Стандартной Библиотеки Шаблонов (STL) в единое целое, позволяя алгоритмам работать с разнородными структурами данных без знания их. . .
Разработка собственного фреймворка для тестирования в C#
UnmanagedCoder 04.05.2025
C# довольно богат готовыми решениями – NUnit, xUnit, MSTest уже давно стали своеобразными динозаврами индустрии. Однако, как и любой динозавр, они не всегда могут протиснуться в узкие коридоры. . .
Распределенная трассировка в Java с помощью OpenTelemetry
Javaican 04.05.2025
Микросервисная архитектура стала краеугольным камнем современной разработки, но вместе с ней пришла и головная боль, знакомая многим — отслеживание прохождения запросов через лабиринт взаимосвязанных. . .
Шаблоны обнаружения сервисов в Kubernetes
Mr. Docker 04.05.2025
Современные Kubernetes-инфраструктуры сталкиваются с серьёзными вызовами. Развертывание в нескольких регионах и облаках одновременно, необходимость обеспечения низкой задержки для глобально. . .
Создаем SPA на C# и Blazor
stackOverflow 04.05.2025
Мир веб-разработки за последние десять лет претерпел коллосальные изменения. Переход от традиционных многостраничных сайтов к одностраничным приложениям (Single Page Applications, SPA) — это. . .
Реализация шаблонов проектирования GoF на C++
NullReferenced 04.05.2025
«Банда четырёх» (Gang of Four или GoF) — Эрих Гамма, Ричард Хелм, Ральф Джонсон и Джон Влиссидес — в 1994 году сформировали канон шаблонов, который выдержал проверку временем. И хотя C++ претерпел. . .
C# и сети: Сокеты, gRPC и SignalR
UnmanagedCoder 04.05.2025
Сетевые технологии не стоят на месте, а вместе с ними эволюционируют и инструменты разработки. В . NET появилось множество решений — от низкоуровневых сокетов, позволяющих управлять каждым байтом. . .
Создание микросервисов с Domain-Driven Design
ArchitectMsa 04.05.2025
Архитектура микросервисов за последние годы превратилась в мощный архитектурный подход, который позволяет разрабатывать гибкие, масштабируемые и устойчивые системы. А если добавить сюда ещё и. . .
Многопоточность в C++: Современные техники C++26
bytestream 04.05.2025
C++ долго жил по принципу «один поток — одна задача» — как старательный солдатик, выполняющий команды одну за другой. В то время, когда процессоры уже обзавелись несколькими ядрами, этот подход стал. . .