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

15,249

netstat -a only lists connected sockets and listening socket.

  -a            Displays all connections and listening ports.

Neither connect nor listen was called on your socket, so it falls outside the purview of netstat -a.

However, since Windows 10, you can use netstat -q.

  -q            Displays all connections, listening ports, and bound
Share:
15,249
user541686
Author by

user541686

Updated on June 05, 2022

Comments

  • user541686
    user541686 almost 2 years

    If you run this example, you'll see the port is never listed by netstat. Why? And how do I make it so?

    #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();
    }
    
  • nos
    nos over 7 years
    Actually - at least on windows 10 netstat has this flag " -q Displays all connections, listening ports, and bound" This shows these incomplete sockets with the word "BOUND" in the State column
  • ikegami
    ikegami over 7 years
    @nos, Thanks. Added to my answer.
  • user541686
    user541686 over 7 years
    Now that's a complete answer. Thanks!
  • Eli Finkel
    Eli Finkel almost 5 years
    The -q flag seems not to work in conjunction with the -b (shows binary/exe name), but it does works with -o (shows owning pid), which is good enough. (or at least this is my experience on Win10 1903)