Skip to content

Instantly share code, notes, and snippets.

@justenwalker
Last active June 20, 2021 16:14
Show Gist options
  • Save justenwalker/2efd144d15b6e2332b905847001e3c0e to your computer and use it in GitHub Desktop.
Save justenwalker/2efd144d15b6e2332b905847001e3c0e to your computer and use it in GitHub Desktop.
Call Windows API for GetExtendedTcpTable and return a Byte Buffer containing the result.
package win32
import (
"syscall"
"unsafe"
)
var (
iphlpapiDLL = syscall.NewLazyDLL("iphlpapi.dll")
procGetExtendedTcpTable = iphlpapiDLL.NewProc("GetExtendedTcpTable")
)
// GetExtendedTcpTable calls the Windows API GetExtendedTcpTable and returns a raw byte buffer
// containing the TCP Table requested. This buffer will need to be converted to the appropriate
// Go structure for use, depending on the combination of ulAf and tableClass requested.
func GetExtendedTcpTable(order uint32, ulAf uint32, tableClass uint32) ([]byte, error) {
var buffer []byte
var pTcpTable *byte
var dwSize uint32
for {
// DWORD GetExtendedTcpTable(
// PVOID pTcpTable,
// PDWORD pdwSize,
// BOOL bOrder,
// ULONG ulAf,
// TCP_TABLE_CLASS TableClass,
// ULONG Reserved
// );
// https://docs.microsoft.com/en-us/windows/desktop/api/iphlpapi/nf-iphlpapi-getextendedtcptable
ret, _, errno := procGetExtendedTcpTable.Call(
uintptr(unsafe.Pointer(pTcpTable)),
uintptr(unsafe.Pointer(&dwSize)),
uintptr(order),
uintptr(ulAf),
uintptr(tableClass),
uintptr(uint32(0)),
)
if ret != 0 {
if syscall.Errno(ret) == syscall.ERROR_INSUFFICIENT_BUFFER {
buffer = make([]byte, int(dwSize))
pTcpTable = &buffer[0]
continue
}
return nil, syscall.Errno(errno)
}
return buffer, nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment