1

I'm trying to find a way to closing a network connection that has been established by another process. My application will run over night automatically. In case the network resource is already in use (which it shouldn't be, but I'm not assuming) I need to close the connection before establishing it with the correct credentials. Again, not assuming the existing connection has the correct access.

Using GetTcpTable() I can search the existing connections for an IP. Now I need to close it. I can find lots of info about closing a connection based on its socket, but I don't know the socket. Can I find out which sockets are used by a given connection (based on remote IP?) or is there some other method of closing a network connection based on remote IP?

Ben
  • 427
  • 5
  • 17
  • SetTcpEntry E.g. https://stackoverflow.com/questions/1672062/how-to-close-a-tcp-connection-by-port – Alex K. Oct 16 '18 at 15:48
  • You should be able to get the process responsible for opening this connection (`GetOwnerModuleFromTcpEntry` looks promising) and than kill this process. That would be much cleaner than closing the connection underneath the process that uses it (if such a way even exists) – SergeyA Oct 16 '18 at 15:48
  • You can get the process PID and terminate the process if that's a possibility. – Hatted Rooster Oct 16 '18 at 15:49
  • @AlexK. any reason not to close this as a duplicate? – SergeyA Oct 16 '18 at 15:50
  • Sounds like maybe you should setup a local firewall to block other apps from accessing the network resource at times your app does not want them to – Remy Lebeau Oct 16 '18 at 22:55

1 Answers1

0

With the help of the comments I put together the following function. Note though that the use of SetTcpEntry on Windows Vista and later requires Administrator privilege. Whilst this answers the explicit question above, I'm still looking for a solution that's user agnostic.

// Fuction to close a collection of network connections
void networkConn::CloseRemoteIP(std::vector<MIB_TCPROW>& rows) {
    for (MIB_TCPROW tcpObject : rows) {
        tcpObject.dwState = MIB_TCP_STATE_DELETE_TCB;

        DWORD ret = SetTcpEntry(&tcpObject);

        if (ret) {
            printf("\nError closing TCP connection. Windows returned: %lu", ret);
        }
    }
}
Ben
  • 427
  • 5
  • 17