Как разорвать сетевое подключение (SetTcpEntry)

Язык Visual Basic на платформе .NET.

Модераторы: Ramzes, Sebas

student-uni
Бывалый
Бывалый
 
Сообщения: 242
Зарегистрирован: 01.10.2005 (Сб) 18:54

Как разорвать сетевое подключение (SetTcpEntry)

Сообщение student-uni » 22.11.2006 (Ср) 11:45

Пытаюсь программно разорвать сетевое подключение.

SetTcpEntry возвращает ошибку 87

Вот код, а в приложении весь файл

подскажите пожалуйста в чём может быть проблема ?

Заранее спасибо
Код: Выделить всё
Option Strict Off
Option Explicit On
Imports System.Runtime.InteropServices

Imports System.Net


Friend Class frmTcpTable
    Inherits System.Windows.Forms.Form
#Region "Windows Form Designer generated code "
    Public Sub New()
        MyBase.New()
        'This call is required by the Windows Form Designer.
        InitializeComponent()
    End Sub
    'Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean)
        If Disposing Then
            If Not components Is Nothing Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(Disposing)
    End Sub
    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer
    Public ToolTip1 As System.Windows.Forms.ToolTip
    Public WithEvents Check1 As System.Windows.Forms.CheckBox
    Public WithEvents Command2 As System.Windows.Forms.Button
    Public WithEvents Command1 As System.Windows.Forms.Button
    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    Friend WithEvents ListView1 As System.Windows.Forms.ListView
    Friend WithEvents ColumnHeader1 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader2 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader3 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader4 As System.Windows.Forms.ColumnHeader
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents ColumnHeader6 As System.Windows.Forms.ColumnHeader
    Friend WithEvents ColumnHeader5 As System.Windows.Forms.ColumnHeader
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Me.components = New System.ComponentModel.Container
        Me.ToolTip1 = New System.Windows.Forms.ToolTip(Me.components)
        Me.Check1 = New System.Windows.Forms.CheckBox
        Me.Command2 = New System.Windows.Forms.Button
        Me.Command1 = New System.Windows.Forms.Button
        Me.ListView1 = New System.Windows.Forms.ListView
        Me.ColumnHeader1 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader2 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader3 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader4 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader5 = New System.Windows.Forms.ColumnHeader
        Me.ColumnHeader6 = New System.Windows.Forms.ColumnHeader
        Me.Button1 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'Check1
        '
        Me.Check1.BackColor = System.Drawing.SystemColors.Control
        Me.Check1.Cursor = System.Windows.Forms.Cursors.Default
        Me.Check1.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Check1.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Check1.Location = New System.Drawing.Point(0, 304)
        Me.Check1.Name = "Check1"
        Me.Check1.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Check1.Size = New System.Drawing.Size(289, 17)
        Me.Check1.TabIndex = 3
        Me.Check1.Text = "Don't show rows for 0.0.0.0 and  127.0.0.1 IP addresses"
        Me.Check1.UseVisualStyleBackColor = False
        '
        'Command2
        '
        Me.Command2.BackColor = System.Drawing.SystemColors.Control
        Me.Command2.Cursor = System.Windows.Forms.Cursors.Default
        Me.Command2.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Command2.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Command2.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Command2.Location = New System.Drawing.Point(407, 304)
        Me.Command2.Name = "Command2"
        Me.Command2.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Command2.Size = New System.Drawing.Size(47, 25)
        Me.Command2.TabIndex = 2
        Me.Command2.Text = "Close"
        Me.Command2.UseVisualStyleBackColor = False
        '
        'Command1
        '
        Me.Command1.Anchor = CType((((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Bottom) _
                    Or System.Windows.Forms.AnchorStyles.Left) _
                    Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles)
        Me.Command1.BackColor = System.Drawing.SystemColors.Control
        Me.Command1.Cursor = System.Windows.Forms.Cursors.Default
        Me.Command1.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Command1.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Command1.Location = New System.Drawing.Point(304, 304)
        Me.Command1.Name = "Command1"
        Me.Command1.RightToLeft = System.Windows.Forms.RightToLeft.No
        Me.Command1.Size = New System.Drawing.Size(97, 25)
        Me.Command1.TabIndex = 1
        Me.Command1.Text = "Get Tcp Table"
        Me.Command1.UseVisualStyleBackColor = False
        '
        'ListView1
        '
        Me.ListView1.Columns.AddRange(New System.Windows.Forms.ColumnHeader() {Me.ColumnHeader1, Me.ColumnHeader2, Me.ColumnHeader3, Me.ColumnHeader4, Me.ColumnHeader5, Me.ColumnHeader6})
        Me.ListView1.FullRowSelect = True
        Me.ListView1.GridLines = True
        Me.ListView1.Location = New System.Drawing.Point(0, 8)
        Me.ListView1.Name = "ListView1"
        Me.ListView1.Size = New System.Drawing.Size(717, 288)
        Me.ListView1.TabIndex = 4
        Me.ListView1.UseCompatibleStateImageBehavior = False
        Me.ListView1.View = System.Windows.Forms.View.Details
        '
        'ColumnHeader1
        '
        Me.ColumnHeader1.Text = "Local Address"
        '
        'ColumnHeader2
        '
        Me.ColumnHeader2.Text = "Local Port"
        '
        'ColumnHeader3
        '
        Me.ColumnHeader3.Text = "Remote Address"
        '
        'ColumnHeader4
        '
        Me.ColumnHeader4.Text = "Remote Port"
        '
        'ColumnHeader5
        '
        Me.ColumnHeader5.Text = "Status"
        '
        'ColumnHeader6
        '
        Me.ColumnHeader6.Width = 400
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(464, 304)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(47, 24)
        Me.Button1.TabIndex = 5
        Me.Button1.Text = "Kill"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'frmTcpTable
        '
        Me.AcceptButton = Me.Command1
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.CancelButton = Me.Command2
        Me.ClientSize = New System.Drawing.Size(729, 331)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.ListView1)
        Me.Controls.Add(Me.Check1)
        Me.Controls.Add(Me.Command2)
        Me.Controls.Add(Me.Command1)
        Me.Font = New System.Drawing.Font("Arial", 8.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle
        Me.MaximizeBox = False
        Me.Name = "frmTcpTable"
        Me.Text = "Get TCP Table using IP Helper API"
        Me.ResumeLayout(False)

    End Sub
#End Region
    '



    Dim iLa, iLp, iRa, iRp As Integer




    <StructLayout(LayoutKind.Sequential)> Public Class MIB_TCPROW
        Public dwState As Integer
        Public dwLocalAddr As Integer
        Public dwLocalPort As Integer
        Public dwRemoteAddr As Integer
        Public dwRemotePort As Integer
    End Class
    '
    Private Const ERROR_BUFFER_OVERFLOW As Short = 111
    Private Const ERROR_INVALID_PARAMETER As Short = 87
    Private Const ERROR_NO_DATA As Short = 232
    Private Const ERROR_NOT_SUPPORTED As Short = 50
    Private Const ERROR_SUCCESS As Short = 0
    '
    Private Const MIB_TCP_STATE_CLOSED As Short = 1
    Private Const MIB_TCP_STATE_LISTEN As Short = 2
    Private Const MIB_TCP_STATE_SYN_SENT As Short = 3
    Private Const MIB_TCP_STATE_SYN_RCVD As Short = 4
    Private Const MIB_TCP_STATE_ESTAB As Short = 5
    Private Const MIB_TCP_STATE_FIN_WAIT1 As Short = 6
    Private Const MIB_TCP_STATE_FIN_WAIT2 As Short = 7
    Private Const MIB_TCP_STATE_CLOSE_WAIT As Short = 8
    Private Const MIB_TCP_STATE_CLOSING As Short = 9
    Private Const MIB_TCP_STATE_LAST_ACK As Short = 10
    Private Const MIB_TCP_STATE_TIME_WAIT As Short = 11
    Private Const MIB_TCP_STATE_DELETE_TCB As Short = 12
    '
    Declare Function GetTcpTable Lib "Iphlpapi" (ByVal pTcpTable As IntPtr, ByRef pdwSize As Integer, ByVal bOrder As Boolean) As Integer
    Declare Function SetTcpEntry Lib "iphlpapi.dll" (ByRef pTcpTable As MIB_TCPROW) As Integer

    Private Sub Command1_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command1.Click
        '
        Dim pdwSize As Integer
        Dim iRetVal As Integer
        Dim i As Integer
        Dim TcpTableRow As MIB_TCPROW
        Dim pStructPointer As IntPtr = IntPtr.Zero
        Dim iNumberOfStructures As Integer
        '
        ListView1.Items.Clear()

        '------
        iRetVal = GetTcpTable(pStructPointer, pdwSize, 0)

        pStructPointer = Marshal.AllocHGlobal(pdwSize)
        iRetVal = GetTcpTable(pStructPointer, pdwSize, 0)
        iNumberOfStructures = Math.Ceiling((pdwSize - 4) / Marshal.SizeOf(GetType(MIB_TCPROW)))

        For i = 0 To iNumberOfStructures - 1
            Dim pStructPointerTemp As IntPtr = New IntPtr(pStructPointer.ToInt32() + 4 + (i * Marshal.SizeOf(GetType(MIB_TCPROW))))

            TcpTableRow = New MIB_TCPROW()
            With TcpTableRow
                .dwLocalAddr = 0
                .dwState = 0
                .dwLocalPort = 0
                .dwRemoteAddr = 0
                .dwRemotePort = 0
            End With
            'Marshal.PtrToStructure(pStructPointerTemp, TcpTableRow)
            TcpTableRow = CType(Marshal.PtrToStructure(pStructPointerTemp, GetType(MIB_TCPROW)), MIB_TCPROW)
            ' Process each MIB_TCPROW here
            If Not ((Check1.CheckState = System.Windows.Forms.CheckState.Checked) And (GetIpFromLong(TcpTableRow.dwLocalAddr) = "0.0.0.0" Or GetIpFromLong(TcpTableRow.dwLocalAddr) = "127.0.0.1")) Then
                '
                'Add the data to the ListView control
                With TcpTableRow
                    Dim itemAdd As ListViewItem
                    itemAdd = ListView1.Items.Add(.dwLocalAddr) '(GetIpFromLong(.dwLocalAddr))
                    itemAdd.SubItems.Add(.dwLocalPort) '(CStr(GetTcpPortNumber(.dwLocalPort)))
                    itemAdd.SubItems.Add(.dwRemoteAddr) '(GetIpFromLong(.dwRemoteAddr))
                    itemAdd.SubItems.Add(.dwRemotePort) '(CStr(GetTcpPortNumber(.dwRemotePort)))
                    itemAdd.SubItems.Add(.dwState) ' (GetState(.dwState))
                    Dim strHn, strIP As String
                    Dim strHnL, strIPL As String
                    strIP = GetIpFromLong(.dwRemoteAddr)
                    strIPL = GetIpFromLong(.dwLocalAddr)
                    Try
                        strHn = Dns.GetHostEntry(strIP).HostName

                    Catch ex As Exception
                        strHn = " Kein "
                    End Try
                    Try
                        strHnL = Dns.GetHostEntry(strIPL).HostName

                    Catch ex As Exception
                        strHnL = " Kein "
                    End Try
                    itemAdd.SubItems.Add(GetIpFromLong(.dwLocalAddr) + " | " + CStr(GetTcpPortNumber(.dwLocalPort)) + " | " + GetIpFromLong(.dwRemoteAddr) + " | " + CStr(GetTcpPortNumber(.dwRemotePort)) + " | " + GetState(.dwState) + " | " + strHn + " | " + strHnL)
                End With
                '
            End If
        Next

        Marshal.FreeHGlobal(pStructPointer)
        '
        '
    End Sub

    Private Sub Command2_Click(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles Command2.Click
        Me.Close()
    End Sub

    Private Function GetIpFromLong(ByRef lngIPAddress As Integer) As String
        '
        Dim arrIpParts() As Byte = BitConverter.GetBytes(lngIPAddress)
        GetIpFromLong = CStr(arrIpParts(0)) & "." & CStr(arrIpParts(1)) & "." & CStr(arrIpParts(2)) & "." & CStr(arrIpParts(3))
        '
    End Function

    Private Function GetState(ByRef lngState As Integer) As String
        '
        Select Case lngState
            Case MIB_TCP_STATE_CLOSED : GetState = "CLOSED"
            Case MIB_TCP_STATE_LISTEN : GetState = "LISTEN"
            Case MIB_TCP_STATE_SYN_SENT : GetState = "SYN_SENT"
            Case MIB_TCP_STATE_SYN_RCVD : GetState = "SYN_RCVD"
            Case MIB_TCP_STATE_ESTAB : GetState = "ESTAB"
            Case MIB_TCP_STATE_FIN_WAIT1 : GetState = "FIN_WAIT1"
            Case MIB_TCP_STATE_FIN_WAIT2 : GetState = "FIN_WAIT2"
            Case MIB_TCP_STATE_CLOSE_WAIT : GetState = "CLOSE_WAIT"
            Case MIB_TCP_STATE_CLOSING : GetState = "CLOSING"
            Case MIB_TCP_STATE_LAST_ACK : GetState = "LAST_ACK"
            Case MIB_TCP_STATE_TIME_WAIT : GetState = "TIME_WAIT"
            Case MIB_TCP_STATE_DELETE_TCB : GetState = "DELETE_TCB"
        End Select
        '
    End Function


    Private Function GetTcpPortNumber(ByRef DWord As Integer) As Integer
        GetTcpPortNumber = DWord / 256 + (DWord Mod 256) * 256
    End Function

    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.SelectedIndexChanged

        Dim lvwP As ListViewItem

        For Each lvwP In ListView1.SelectedItems

            iLa = Convert.ToInt32(lvwP.SubItems.Item(0).Text)
            iLp = Convert.ToInt32(lvwP.SubItems.Item(1).Text)
            iRa = Convert.ToInt32(lvwP.SubItems.Item(2).Text)
            iRp = Convert.ToInt32(lvwP.SubItems.Item(3).Text)


        Next


        'MsgBox(ListView1.SelectedItems.SubItems.Item(0).Text)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'ListView1.SelectedListViewItemCollection()
        '
        'Dim pdwSize As Integer
        'Dim iRetVal As Integer
        'Dim i As Integer
        Dim TcpTableRow As MIB_TCPROW
        'Dim pStructPointer As IntPtr = IntPtr.Zero
        'Dim iNumberOfStructures As Integer
        '
        'ListView1.Items.Clear()

        '------
        'iRetVal = GetTcpTable(pStructPointer, pdwSize, 0)

        'pStructPointer = Marshal.AllocHGlobal(pdwSize)
        'iRetVal = GetTcpTable(pStructPointer, pdwSize, 0)
        'iNumberOfStructures = Math.Ceiling((pdwSize - 4) / Marshal.SizeOf(GetType(MIB_TCPROW)))

        'For i = 0 To iNumberOfStructures - 1
        'Dim pStructPointerTemp As IntPtr = New IntPtr(pStructPointer.ToInt32() + 4 + (i * Marshal.SizeOf(GetType(MIB_TCPROW))))

        TcpTableRow = New MIB_TCPROW '()
        With TcpTableRow
            .dwLocalAddr = iLa
            .dwState = MIB_TCP_STATE_DELETE_TCB
            .dwLocalPort = iLp
            .dwRemoteAddr = iRa
            .dwRemotePort = iRp
        End With
        'Marshal.PtrToStructure(pStructPointerTemp, TcpTableRow)
        'TcpTableRow = CType(Marshal.PtrToStructure(pStructPointerTemp, GetType(MIB_TCPROW)), MIB_TCPROW)

        Dim lngRetValue As Int32

        lngRetValue = SetTcpEntry(TcpTableRow)
        '
        If lngRetValue = 0 Then
            MsgBox("The connection was deleted successfully.", vbInformation)
        Else
            MsgBox("Cannot delete the connection. | " + lngRetValue.ToString + " | ", vbExclamation)
        End If


        ' Process each MIB_TCPROW here
        'If Not ((Check1.CheckState = System.Windows.Forms.CheckState.Checked) And (GetIpFromLong(TcpTableRow.dwLocalAddr) = "0.0.0.0" Or GetIpFromLong(TcpTableRow.dwLocalAddr) = "127.0.0.1")) Then
        '    '
        '    'Add the data to the ListView control
        '    With TcpTableRow
        '        Dim itemAdd As ListViewItem
        '        itemAdd = ListView1.Items.Add(GetIpFromLong(.dwLocalAddr))
        '        itemAdd.SubItems.Add(CStr(GetTcpPortNumber(.dwLocalPort)))
        '        itemAdd.SubItems.Add(GetIpFromLong(.dwRemoteAddr))
        '        itemAdd.SubItems.Add(CStr(GetTcpPortNumber(.dwRemotePort)))
        '        itemAdd.SubItems.Add(GetState(.dwState))
        '    End With
        '    '
        'End If
        'Next

        'Marshal.FreeHGlobal(pStructPointer)
    End Sub


   

End Class
Вложения
GetTcpTable.NET.zip
(54.53 Кб) Скачиваний: 81

Neco
Новичок
Новичок
 
Сообщения: 29
Зарегистрирован: 06.07.2005 (Ср) 1:21

Сообщение Neco » 22.11.2006 (Ср) 20:34

87 - это параметр задан неверно
обычно это ошибка рода "передал значение переменной вместо указателя".
кстати в описаниях структур лучше использовать int32, а не integer
и может быть всё-таки это должна быть именно структура:
Код: Выделить всё
<StructLayout(LayoutKind.Sequential)> _
Private Structure METAHEADER
   Public mtType As Int16
   Public mtHeaderSize As Int16
   Public mtVersion As Int16
   Public mtSize As Int32
   Public mtNoObjects As Int16
   Public mtMaxRecord As Int32
   Public mtNoParameters As Int16
End Structure

это я про твою mib_tcprow - не нашёл её описания мой AV, а из сишки выдирать влом.
p.s. а почему не пересядешь на 2005, если не секрет? такие простыни неудобно ни выкладывать ни просматривать.

student-uni
Бывалый
Бывалый
 
Сообщения: 242
Зарегистрирован: 01.10.2005 (Сб) 18:54

Сообщение student-uni » 22.11.2006 (Ср) 21:45

[url]
http://msdn.microsoft.com/library/defau ... TCPROW.asp
[/url]
Microsoft Windows CE .NET 4.2

MIB_TCPROW
This structure contains information for a TCP connection.

typedef struct _MIB_TCPROW {
DWORD dwState;
DWORD dwLocalAddr;
DWORD dwLocalPort;
DWORD dwRemoteAddr;
DWORD dwRemotePort;
} MIB_TCPROW, *PMIB_TCPROW;
Members
dwState
Specifies the state of the TCP connection. The following list shows the possible values. This member can have one of these values:
MIB_TCP_STATE_CLOSED
MIB_TCP_STATE_LISTEN
MIB_TCP_STATE_SYN_SENT
MIB_TCP_STATE_SYN_RCVD
MIB_TCP_STATE_ESTAB
MIB_TCP_STATE_FIN_WAIT1
MIB_TCP_STATE_FIN_WAIT2
MIB_TCP_STATE_CLOSE_WAIT
MIB_TCP_STATE_CLOSING
MIB_TCP_STATE_LAST_ACK
MIB_TCP_STATE_TIME_WAIT
MIB_TCP_STATE_DELETE_TCB
dwLocalAddr
Specifies the address for the connection on the local computer.
dwLocalPort
Specifies the port number for the connection on the local computer.
dwRemoteAddr
Specifies the address for the connection on the remote computer.
dwRemotePort
Specifies the port number for the connection on the remote computer.
Remarks
The port numbers are listed in the TCP table in network order.

Requirements
OS Versions: Windows CE 3.0 and later.
Header: Iprtrmib.h.

See Also
IPHelper Structures | MIB_TCPTABLE | SetTcpEntry


student-uni
Бывалый
Бывалый
 
Сообщения: 242
Зарегистрирован: 01.10.2005 (Сб) 18:54

Сообщение student-uni » 22.11.2006 (Ср) 21:49

У меня есть вариант на вб 6
он вроде работает
вот в прицепном файле
может поймёшь в чём собака
Вложения
TcpTable.rar
(16.1 Кб) Скачиваний: 125

Neco
Новичок
Новичок
 
Сообщения: 29
Зарегистрирован: 06.07.2005 (Ср) 1:21

Сообщение Neco » 22.11.2006 (Ср) 23:15

дык я ж тебе уже предложил местоположение пса - неправильно объявил структуру

student-uni
Бывалый
Бывалый
 
Сообщения: 242
Зарегистрирован: 01.10.2005 (Сб) 18:54

Сообщение student-uni » 23.11.2006 (Чт) 19:02

да переделал я по-твоему
всё тоже 87


Вернуться в Visual Basic .NET

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 94

    TopList