?
Solved

Programmaticaly close TCP Connection(s)

Posted on 2010-01-11
16
Medium Priority
?
2,425 Views
Last Modified: 2013-12-17
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.
0
Comment
Question by:_ColdFire_
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 3
  • 3
  • +1
16 Comments
 
LVL 11

Expert Comment

by:srikanthreddyn143
ID: 26287895
0
 

Author Comment

by:_ColdFire_
ID: 26288475
Don't think it might help.
0
 
LVL 7

Expert Comment

by:HalfAsleep
ID: 26288906
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?
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 

Author Comment

by:_ColdFire_
ID: 26288948
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..
0
 
LVL 11

Expert Comment

by:srikanthreddyn143
ID: 26289436


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

tcpClient.Close()

0
 
LVL 11

Expert Comment

by:srikanthreddyn143
ID: 26289440
is that the one you are asking for?
0
 
LVL 9

Expert Comment

by:magicdlf
ID: 26290004
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.
0
 
LVL 7

Expert Comment

by:HalfAsleep
ID: 26290884
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

0
 

Author Comment

by:_ColdFire_
ID: 26291222
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'.      
0
 

Author Comment

by:_ColdFire_
ID: 26291233
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

0
 

Author Comment

by:_ColdFire_
ID: 26291251
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 ;)
0
 

Author Comment

by:_ColdFire_
ID: 26291653
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
0
 

Author Comment

by:_ColdFire_
ID: 26291872
sorry last comment is not for this question :P
0
 
LVL 9

Expert Comment

by:magicdlf
ID: 26292056
Dim ps() As Process = Process.GetProcessesByName("process")
Do you have a process called "process"?
0
 

Author Comment

by:_ColdFire_
ID: 26292136
that post is for :

http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Studio_.NET_2005/Q_25043959.html

and no, that's not a real name of process... everything else is same as in my app..
0
 
LVL 9

Accepted Solution

by:
magicdlf earned 2000 total points
ID: 26341365
I believe your question is already solved. Please close this thread and award points. : )
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
Suggested Courses

741 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question