为什么netstat没有列出我的socket的开放端口?

时间:2016-11-29 21:13:45

标签: c sockets winapi winsock 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();
}

1 个答案:

答案 0 :(得分:12)

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

  -a            Displays all connections and listening ports.

您的套接字上未调用connectlisten,因此它超出了netstat -a的范围。

但是,从Windows 10开始,您可以使用netstat -q

  -q            Displays all connections, listening ports, and bound