2

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.

aderesh
  • 927
  • 10
  • 22
  • 1
    Close a TCP connection by port -->https://stackoverflow.com/questions/1672062/how-to-close-a-tcp-connection-by-port – Ross Bush May 01 '19 at 16:38
  • Thanks, @RossBush, I think this question is a duplicate of the one you've provided. Will check it. – aderesh May 05 '19 at 02:38

1 Answers1

2

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.

Jebiel
  • 52
  • 6
  • You don't need to spawn a `netstat` process, you can enumerate the connections and owner PIDs directly by using `GetTcpTable2()` or `GetExtendedTcpTable()` instead – Remy Lebeau May 01 '19 at 17:29
  • That's also a good way to do it. And probably with a smaller overhead. – Jebiel May 01 '19 at 17:33
  • This isn't about overhead as much as it is about correctness. The layout of the structures used by the API calls is well defined. The layout and formatting of the `netstat` tool isn't. There are no implied or expressed guarantees, that the latter won't change, without notice. – IInspectable May 03 '19 at 07:38