Link to home
Start Free TrialLog in
Avatar of _ColdFire_
_ColdFire_Flag for United Kingdom of Great Britain and Northern Ireland

asked on

Programmaticaly close TCP Connection(s)

Hi I would like to know, how can i close TCP connections programmatically.
Preferable languange is VB.NET.

If I need my application to list current TCP connections and then to have an option to close them.
Avatar of srikanthreddyn143
srikanthreddyn143

Avatar of _ColdFire_

ASKER

Don't think it might help.
Do you want to list all the current connected sockets on your entire system, or do you need to list your program's current connected sockets?
The thing is, I have to list TCP Connections for specific process (process.exe) - It's not my application.

How can i kill TCP connection using ip adress ( Which is 127.0.0.1 ) and Port :47163 or 53172 .... whatever it is..


Dim tcpClient As New System.Net.Sockets.TcpClient()
        tcpClient.Connect("127.0.0.1", 47163)

tcpClient.Close()

is that the one you are asking for?
If you want to terminate the TCP connection created by other process, I am afraid you have to use P/Invoke to call some WINAPI to achieve this. Take a look at this: http://www.debugging.com/bug/4715
It's written in C#, but you can convert it to VB.NET by this: http://www.developerfusion.com/tools/convert/csharp-to-vb/
No guarantee that it's working, but just give you a rough idea what need to be done for the task.
For those wandering what the above links are referring to, it is the IP helper API from Microsoft.

http://msdn.microsoft.com/en-us/library/aa366073(VS.85).aspx

I converted code to VB.NET and have a few errors..

      buffSubPointer = DirectCast((CInt(buffer) + 4), IntPtr)  -
Value of type 'Integer' cannot be converted to 'System.IntPtr'.      

and

buffSubPointer = DirectCast((CInt(buffSubPointer) + sizeOfTCPROW), IntPtr)
Value of type 'Integer' cannot be converted to 'System.IntPtr'.      
Whole code looks like that
Imports System
Imports System.Collections
Imports System.Runtime.InteropServices

Public Class conn
    'Enumeration of the states
    Public Enum State
        All = 0
        Closed = 1
        Listen = 2
        Syn_Sent = 3
        Syn_Rcvd = 4
        Established = 5
        Fin_Wait1 = 6
        Fin_Wait2 = 7
        Close_Wait = 8
        Closing = 9
        Last_Ack = 10
        Time_Wait = 11
        Delete_TCB = 12
    End Enum
    'Connection info
    Private Structure MIB_TCPROW
        Public dwState As Integer
        Public dwLocalAddr As Integer
        Public dwLocalPort As Integer
        Public dwRemoteAddr As Integer
        Public dwRemotePort As Integer
    End Structure
    'API to get list of connections
    <DllImport("iphlpapi.dll")> _
    Private Shared Function GetTcpTable(ByVal pTcpTable As IntPtr, ByRef pdwSize As Integer, ByVal bOrder As Boolean) As Integer
    End Function
    'API to change status of connection
    'private static extern int SetTcpEntry(MIB_TCPROW tcprow);
    <DllImport("iphlpapi.dll")> _
      Private Shared Function SetTcpEntry(ByVal pTcprow As IntPtr) As Integer
    End Function
    'Convert 16-bit value from network to host byte order
    <DllImport("wsock32.dll")> _
   Private Shared Function ntohs(ByVal netshort As Integer) As Integer
    End Function
    'Convert 16-bit value back again
    <DllImport("wsock32.dll")> _
    Private Shared Function htons(ByVal netshort As Integer) As Integer
    End Function

    'Close all connection to the remote IP
    Public Shared Sub CloseRemoteIP(ByVal IP As String)
        Dim rows As MIB_TCPROW() = GetTcpTable()
        For i As Integer = 0 To rows.Length - 1
            If rows(i).dwRemoteAddr = IPStringToInt(IP) Then
                rows(i).dwState = CInt(State.Delete_TCB)
                Dim ptr As IntPtr = GetPtrToNewObject(rows(i))
                Dim ret As Integer = SetTcpEntry(ptr)
            End If
        Next
    End Sub

    'Close all connections at current local IP
    Public Shared Sub CloseLocalIP(ByVal IP As String)
        Dim rows As MIB_TCPROW() = GetTcpTable()
        For i As Integer = 0 To rows.Length - 1
            If rows(i).dwLocalAddr = IPStringToInt(IP) Then
                rows(i).dwState = CInt(State.Delete_TCB)
                Dim ptr As IntPtr = GetPtrToNewObject(rows(i))
                Dim ret As Integer = SetTcpEntry(ptr)
            End If
        Next
    End Sub
    'Closes all connections to the remote port
    Public Shared Sub CloseRemotePort(ByVal port As Integer)
        Dim rows As MIB_TCPROW() = GetTcpTable()
        For i As Integer = 0 To rows.Length - 1
            If port = ntohs(rows(i).dwRemotePort) Then
                rows(i).dwState = CInt(State.Delete_TCB)
                Dim ptr As IntPtr = GetPtrToNewObject(rows(i))
                Dim ret As Integer = SetTcpEntry(ptr)
            End If
        Next
    End Sub
    'Closes all connections to the local port
    Public Shared Sub CloseLocalPort(ByVal port As Integer)
        Dim rows As MIB_TCPROW() = GetTcpTable()
        For i As Integer = 0 To rows.Length - 1
            If port = ntohs(rows(i).dwLocalPort) Then
                rows(i).dwState = CInt(State.Delete_TCB)
                Dim ptr As IntPtr = GetPtrToNewObject(rows(i))
                Dim ret As Integer = SetTcpEntry(ptr)
            End If
        Next
    End Sub
    'Close a connection by returning the connectionstring
    Public Shared Sub CloseConnection(ByVal connectionstring As String)
        Try
            'Split the string to its subparts
            Dim parts As String() = connectionstring.Split("-"c)
            If parts.Length <> 4 Then
                Throw New Exception("Invalid connectionstring - use the one provided by Connections.")
            End If
            Dim loc As String() = parts(0).Split(":"c)
            Dim [rem] As String() = parts(1).Split(":"c)
            Dim locaddr As String() = loc(0).Split("."c)
            Dim remaddr As String() = [rem](0).Split("."c)
            'Fill structure with data
            Dim row As New MIB_TCPROW()
            row.dwState = 12
            Dim bLocAddr As Byte() = New Byte() {Byte.Parse(locaddr(0)), Byte.Parse(locaddr(1)), Byte.Parse(locaddr(2)), Byte.Parse(locaddr(3))}
            Dim bRemAddr As Byte() = New Byte() {Byte.Parse(remaddr(0)), Byte.Parse(remaddr(1)), Byte.Parse(remaddr(2)), Byte.Parse(remaddr(3))}
            row.dwLocalAddr = BitConverter.ToInt32(bLocAddr, 0)
            row.dwRemoteAddr = BitConverter.ToInt32(bRemAddr, 0)
            row.dwLocalPort = htons(Integer.Parse(loc(1)))
            row.dwRemotePort = htons(Integer.Parse([rem](1)))
            'Make copy of the structure into memory and use the pointer to call SetTcpEntry
            Dim ptr As IntPtr = GetPtrToNewObject(row)
            Dim ret As Integer = SetTcpEntry(ptr)
            If ret = -1 Then
                Throw New Exception("Unsuccessful")
            End If
            If ret = 65 Then
                Throw New Exception("User has no sufficient privilege to execute this API successfully")
            End If
            If ret = 87 Then
                Throw New Exception("Specified port is not in state to be closed down")
            End If
            If ret <> 0 Then
                Throw New Exception("Unknown error (" & ret & ")")
            End If
        Catch ex As Exception
            Throw New Exception((("CloseConnection failed (" & connectionstring & ")! [") + ex.[GetType]().ToString() & ",") + ex.Message & "]")
        End Try
    End Sub
    'Gets all connections
    Public Shared Function Connections() As String()
        Return Connections(State.All)
    End Function
    'Gets a connection list of connections with a defined state
    Public Shared Function Connections(ByVal state__1 As State) As String()
        Dim rows As MIB_TCPROW() = GetTcpTable()

        Dim arr As New ArrayList()

        For Each row As MIB_TCPROW In rows
            If state__1 = State.All OrElse state__1 = DirectCast(row.dwState, State) Then
                Dim localaddress As String = (IPIntToString(row.dwLocalAddr) & ":") + ntohs(row.dwLocalPort)
                Dim remoteaddress As String = (IPIntToString(row.dwRemoteAddr) & ":") + ntohs(row.dwRemotePort)
                arr.Add((((localaddress & "-") + remoteaddress & "-") + DirectCast(row.dwState, State).ToString() & "-") + row.dwState)
            End If
        Next

        Return DirectCast(arr.ToArray(GetType(System.String)), String())
    End Function
    'The function that fills the MIB_TCPROW array with connectioninfos
    Private Shared Function getTcpTable() As MIB_TCPROW()
        Dim buffer As IntPtr = IntPtr.Zero
        Dim allocated As Boolean = False
        Try
            Dim iBytes As Integer = 0
            getTcpTable(IntPtr.Zero, iBytes, False)
            'Getting size of return data
            buffer = Marshal.AllocCoTaskMem(iBytes)
            'allocating the datasize
            allocated = True
            getTcpTable(buffer, iBytes, False)
            'Run it again to fill the memory with the data
            Dim structCount As Integer = Marshal.ReadInt32(buffer)
            ' Get the number of structures
            Dim buffSubPointer As IntPtr = buffer
            'Making a pointer that will point into the buffer
            buffSubPointer = DirectCast((CInt(buffer) + 4), IntPtr)
            'Move to the first data (ignoring dwNumEntries from the original MIB_TCPTABLE struct)
            Dim tcpRows As MIB_TCPROW() = New MIB_TCPROW(structCount - 1) {}
            'Declaring the array
            'Get the struct size
            Dim tmp As New MIB_TCPROW()
            Dim sizeOfTCPROW As Integer = Marshal.SizeOf(tmp)
            'Fill the array 1 by 1
            For i As Integer = 0 To structCount - 1
                tcpRows(i) = DirectCast(Marshal.PtrToStructure(buffSubPointer, GetType(MIB_TCPROW)), MIB_TCPROW)
                'copy struct data
                'move to next structdata
                buffSubPointer = DirectCast((CInt(buffSubPointer) + sizeOfTCPROW), IntPtr)
            Next

            Return tcpRows
        Catch ex As Exception
            Throw New Exception(("getTcpTable failed! [" & ex.[GetType]().ToString() & ",") + ex.Message & "]")
        Finally
            If allocated Then
                Marshal.FreeCoTaskMem(buffer)
                'Free the allocated memory
            End If
        End Try
    End Function
    Private Shared Function GetPtrToNewObject(ByVal obj As Object) As IntPtr
        Dim ptr As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(obj))
        Marshal.StructureToPtr(obj, ptr, False)
        Return ptr
    End Function
    'Convert an IP string to the INT value
    Private Shared Function IPStringToInt(ByVal IP As String) As Integer
        If IP.IndexOf(".") < 0 Then
            Throw New Exception("Invalid IP address")
        End If
        Dim addr As String() = IP.Split("."c)
        If addr.Length <> 4 Then
            Throw New Exception("Invalid IP address")
        End If
        Dim bytes As Byte() = New Byte() {Byte.Parse(addr(0)), Byte.Parse(addr(1)), Byte.Parse(addr(2)), Byte.Parse(addr(3))}
        Return BitConverter.ToInt32(bytes, 0)
    End Function
    'Convert an IP integer to IP string
    Private Shared Function IPIntToString(ByVal IP As Integer) As String
        Dim addr As Byte() = System.BitConverter.GetBytes(IP)
        Return (((addr(0) & ".") + addr(1) & ".") + addr(2) & ".") + addr(3)
    End Function
End Class

Open in new window

Also, I don't get it , should i create some datagridview or something where those connections will be displayed and i can close them...

I need all connections to my pc to be displayed (TCP, UPD) and I will find which ones i need to close myself ;)
Loadtext(Textbox1.Text) - Filters all chat messages and leaves just sytem (join / Leave) messages.
Loadtext2(Textbox1.Text) - Filters those join and leave messages and insert into datagridview
sorry last comment is not for this question :P
Dim ps() As Process = Process.GetProcessesByName("process")
Do you have a process called "process"?
that post is for :

https://www.experts-exchange.com/questions/25043959/VB-NET-Save-Load-Filter-text.html

and no, that's not a real name of process... everything else is same as in my app..
ASKER CERTIFIED SOLUTION
Avatar of magicdlf
magicdlf

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial