Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a socket connection of other application?

Tags:

.net

winapi

Similarly to what TCPView can do.

Are there any ways to do it in .net or in winapi?

I need to automate this process to simulate connection lost for my integration tests.

Also, I cannot use http://www.nirsoft.net/utils/cports.html since it's blocked by my company.

like image 693
aderesh Avatar asked Feb 02 '26 13:02

aderesh


1 Answers

Now when a program wants to create a socket, it creates a process that listens to a pre-defined port of choice.

As mentioned in this thread Manually close a port from commandline, the socket is bound to the process that created it. Meaning it would automatically be freed, when the process terminates. With I guess cports (the program you referred) esentially does.

Now you could use the built-in program in windows "netstat" to get a list of reserved ports, and the id of processes that keeps them open.

Take a look at this link Check Open TCP/IP Ports in Windows.

There are multiple ways to run a program, and then get the 'std output' for further processing. Here's a link that shows how Execute a Command in C#.

Summary: (My immediate approach would be...) Make a call from C# to netstat, get the id, from the port of your interest. And the call "Taskkill /PID the_id /F".

Give it a try, hope it works for you.

like image 51
Jebiel Avatar answered Feb 04 '26 03:02

Jebiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!