I'm using the ctypes module to call GetTcpTable2
.
I've been slowly converting the example here in C++ to Python; but am getting crash during a field access.
if __name__ == "__main__":
ptcp_table = POINTER(MIB_TCPTABLE2)()
ptcp_table = cast(create_string_buffer(sizeof(MIB_TCPTABLE2)),
POINTER(MIB_TCPTABLE2))
ip_addr = in_addr()
size = c_ulong(sizeof(MIB_TCPTABLE2))
retval = GetTcpTable2(ptcp_table, byref(size), TRUE)
if retval == ERROR_INSUFFICIENT_BUFFER:
ptcp_table = cast(create_string_buffer(size.value),
POINTER(MIB_TCPTABLE2))
if not ptcp_table:
#throw error
pass
retval = GetTcpTable2(ptcp_table, byref(size), TRUE)
if retval == NO_ERROR:
print("Entries %d" % ptcp_table[0].dwNumEntries)
for i in range(0, ptcp_table[0].dwNumEntries):
print(ptcp_table[0].table[i])
#ip_addr.S_un.S_addr = ptcp_table[0].table[i].dwLocalAddr
#ip_addr_string = inet_nota(ip_addr)
#print(ip_addr_string)
#print(string_at(ip_addr_string))
It crashes when trying to access dwLocalAddr
apart of table[i]
.
ptcp_table[0].table[i].dwLocalAddr
However it doesn't crash when just printing ptcp_table[0].table[i]
.
I've tried printing and accessing other fields; but Python just crashes.
Here are my struct definitions:
class MIB_TCPROW2(Structure):
_fields_ = [
("dwState", c_ulong),
("dwLocalAddr", c_ulong),
("dwLocalPort", c_ulong),
("dwRemoteAddr", c_ulong),
("dwRemotePort", c_ulong),
("dwOwningPid", c_ulong),
("dwOffloadState", c_int)
]
class MIB_TCPTABLE2(Structure):
_fields_ = [
("dwNumEntries", c_ulong),
("table", POINTER(MIB_TCPROW2))
]
Definition of GetTcpTable2
:
GetTcpTable2 = windll.iphlpapi.GetTcpTable2
GetTcpTable2.argtypes = [POINTER(MIB_TCPTABLE2), POINTER(c_ulong), c_char]
GetTcpTable2.restype = c_ulong
I have a small hunch that in the definition of the MIB_TCPTABLE2
struct; the documentation says that table
is an array of MIB_TCPROW2
size ANY_SIZE
; and further inspection is that ANY_SIZE
is 1 from checking the iphlpapi.h
file. And I know that the size of POINTER(MIB_TCPROW2)
doesn't equal the size of MIB_TCPROW2
.