private static List<IPConnection> queryTCPv4Connections() {
List<IPConnection> conns = new ArrayList<>();
// Get size needed
try (CloseableIntByReference sizePtr = new CloseableIntByReference()) {
int ret = IPHLP.GetExtendedTcpTable(null, sizePtr, false, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
if (ret == WinError.ERROR_SUCCESS) {
// Get buffer and populate table
int size = sizePtr.getValue();
Memory buf = new Memory(size);
do {
ret = IPHLP.GetExtendedTcpTable(buf, sizePtr, false, AF_INET, TCP_TABLE_OWNER_PID_ALL, 0);
if (ret == WinError.ERROR_INSUFFICIENT_BUFFER) {
size = sizePtr.getValue();
buf.close();
buf = new Memory(size);
}
} while (ret == WinError.ERROR_INSUFFICIENT_BUFFER);
MIB_TCPTABLE_OWNER_PID tcpTable = new MIB_TCPTABLE_OWNER_PID(buf);
for (int i = 0; i < tcpTable.dwNumEntries; i++) {
MIB_TCPROW_OWNER_PID row = tcpTable.table[i];
conns.add(new IPConnection("tcp4", ParseUtil.parseIntToIP(row.dwLocalAddr),
ParseUtil.bigEndian16ToLittleEndian(row.dwLocalPort),
ParseUtil.parseIntToIP(row.dwRemoteAddr),
ParseUtil.bigEndian16ToLittleEndian(row.dwRemotePort), stateLookup(row.dwState), 0, 0,
row.dwOwningPid));
}
buf.close();
}
}
return conns;
}