drxt70655
drxt70655
2017-11-21 00:22

调用GetExtendedTcpTable时为空响应()

已采纳

I am new to Go, and I need to catch net information in Windows. I tried to call GetExtendedTcpTable() with pointers to byte arrays as params but get nothing after the call.

var (
    iphelp   = syscall.NewLazyDLL("iphlpapi.dll")
    tcptable = iphelp.NewProc("GetExtendedTcpTable")
)

var (
    buffer [20000]byte
    table  [20000]byte
    length int
)

res1, res2, err := tcptable.Call(
    uintptr(unsafe.Pointer(&buffer)),
    uintptr(unsafe.Pointer(&length)),
    1,
    syscall.AF_INET,
    uintptr(unsafe.Pointer(&table)),
    0,
)

I expected some data in 'buffer' and 'table', but there are only 0. What am I doing wrong?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dongxie2613 dongxie2613 4年前

    Your code has two errors. First, you pass in legnth=0, which causes GetExtendedTcpTable() to return ERROR_INSUFFICIENT_BUFFER 122 (0x7A). Then, the fifth parameter is not a pointer to the table itself, but an input parameter that states the class (type) of the table to return (write into parameter 1. Here is a corrected version to get over these hurdles:

    import (
            "fmt"
            "syscall"
            "unsafe"
    )
    
    const (
            TCP_TABLE_BASIC_LISTENER = iota
            TCP_TABLE_BASIC_CONNECTIONS
            TCP_TABLE_BASIC_ALL
            TCP_TABLE_OWNER_PID_LISTENER
            TCP_TABLE_OWNER_PID_CONNECTIONS
            TCP_TABLE_OWNER_PID_ALL
            TCP_TABLE_OWNER_MODULE_LISTENER
            TCP_TABLE_OWNER_MODULE_CONNECTIONS
            TCP_TABLE_OWNER_MODULE_ALL
    )
    
    func main() {
            var table [2000]byte
            var length int = len(table)
    
            iphelp := syscall.NewLazyDLL("iphlpapi.dll")
            tcptable := iphelp.NewProc("GetExtendedTcpTable")
    
            length = len(table)
    
            res1, res2, err := tcptable.Call(
                    uintptr(unsafe.Pointer(&table)),
                    uintptr(unsafe.Pointer(&length)),
                    1,
                    syscall.AF_INET,
                    TCP_TABLE_BASIC_LISTENER,
                    0,
            )
    
            fmt.Println(res1, res2, length, err)
            fmt.Println(table)
    }
    

    I figured this out by inspecting the return code of the GetExtendedTcpTable(). Microsoft system error codes are listed on: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

    点赞 评论 复制链接分享

相关推荐