为什么 netstat 没有列出我的套接字的开放端口?

Why is my socket's open port not listed by netstat?

如果您 运行 这个例子,您会看到该端口从未被 netstat 列出。为什么?我该怎么做?

#include <WinSock.h>
#include <io.h>
#include <stdio.h>

#pragma comment(lib, "WS2_32")

int main() {
    WORD wVers = MAKEWORD(2, 2);
    WSADATA wsa;
    WSAStartup(wVers, &wsa);
    SOCKET sock = socket(AF_INET, SOCK_STREAM, 6);
    if (sock != INVALID_SOCKET) {
        struct sockaddr_in addr = { 0 };
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        int addrlen = sizeof(addr);
        bind(sock, (struct sockaddr *)&addr, addrlen);
        if (getsockname(sock, (struct sockaddr *)&addr, &addrlen) == 0) {
            fprintf(stdout, "HANDLE = %d, port = %d\n", sock, addr.sin_port);
            fflush(stdout);
            system("netstat -a -n");
        }
        closesocket(sock);
    }
    WSACleanup();
}

netstat -a 仅列出连接的套接字和侦听套接字。

  -a            Displays all connections and listening ports.

connectlisten 都未在您的套接字上调用,因此它不在 netstat -a 的范围内。

但是,由于 Windows 10,您可以使用 netstat -q

  -q            Displays all connections, listening ports, and bound