_ColdFire_
asked on
Convert integer to intptr problems
Hi , I have the following error:
Value of type 'Integer' cannot be converted to 'System.IntPtr'
Code is included:
Value of type 'Integer' cannot be converted to 'System.IntPtr'
Code is included:
Imports System
Imports System.Collections
Imports System.Runtime.InteropServices
Public Class connform
'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
ASKER
It looks that it fixed a problem, but not for the other line which is:
buffSubPointer = DirectCast((CInt(buffSubPo inter) + sizeOfTCPROW), IntPtr)
buffSubPointer = DirectCast((CInt(buffSubPo
ASKER
there was two lines with same error, one supposed to be fixed now ;)
ASKER
I changed it from
buffSubPointer = DirectCast((CInt(buffSubPo inter) + sizeOfTCPROW), IntPtr)
to
buffSubPointer = New IntPtr((CInt(buffSubPointe r) + sizeOfTCPROW))
Is that ok?!
buffSubPointer = DirectCast((CInt(buffSubPo
to
buffSubPointer = New IntPtr((CInt(buffSubPointe
Is that ok?!
ASKER
Also, this code should return those values somewhere, I mean it should be some datagridview or something where all connections are displayed and can be closed... (I found this code as C# and converted to vb.net)
I guess it's like:
buffSubPointer = New IntPtr(buffSubPointer.ToIn t32 + sizeOfTCPROW)
buffSubPointer = New IntPtr(buffSubPointer.ToIn
ASKER
whats about displaying connection, how can i list them id datagridview with option to close them?
Try to debug and see the property: "Connections". Your connections should be all there. Put them into the datagridview.
btw, you only defined a class. Did you create an instance of the class?
btw, you only defined a class. Did you create an instance of the class?
ASKER
I posted all code i have... I don't know how to get it to work... can you post a complete solution project using that code above/?
I wish I could. I think I can provide you a C# solution, but you need to translate it into VB.NET.
Btw, is this a homework or something like that? Because the EE's rule doen't allow us to do so. Usually you will get hints about that and you need to find out the answer yourself.
Btw, is this a homework or something like that? Because the EE's rule doen't allow us to do so. Usually you will get hints about that and you need to find out the answer yourself.
ASKER
Ok, it will be fine if it's C# solution if it works ;) There should be form with datagridview or listview to view current tcp connections and option to disconnect them. :P
ASKER
It's not homework, I'm making this application for myself for a few things.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
thanks man, Ill check it asap :P
ASKER
I created datagridview1 button1 and timer1 , it shows connections but does not disconnect them..
ASKER
OK, it tarded, thanks for help man, it works :)
buffSubPointer = DirectCast((CInt(buffer) + 4), IntPtr)
to
buffSubPointer = New IntPtr(buffer.ToInt32 + 4)
And please attach the error messages