locked
Winsock function bind() could not detect the used port RRS feed

  • Question

  • Hi,

    I used the bind() function to bind a socket with a port number. From the bind()'s MSDN document, it will give error if it tries to bind an used port number. I used the below codes to test whether a port number is currently used. The below code can tell correctly whether a port number is used under windows XP; but it does not work correctly under windows 2003 and windows Vista. Any suggentions are appreciated.



    Code Snippet

    #include "stdafx.h"
    #include <Winsock2.h>
    #include <iostream>
    #include "winsock2.h"

    bool CheckPortAvailable(int portnum){
      //----------------------
      // Initialize Winsock
      WSADATA wsaData;
      int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
      if (iResult != NO_ERROR) {
        return false;
      }
     
      //----------------------
      // Create a SOCKET for listening for
      // incoming connection requests
      SOCKET ListenSocket;
      ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
      if (ListenSocket == INVALID_SOCKET) {
        WSACleanup();
        return false;
      }

     
      //----------------------
      // The sockaddr_in structure specifies the address family,
      // IP address, and port for the socket that is being bound.
      sockaddr_in service;
      service.sin_addr.s_addr = inet_addr("127.0.0.1");
      service.sin_family = AF_INET;
      service.sin_port = htons((u_short)portnum);

      //----------------------
      // Bind the socket.
      if (bind( ListenSocket,     (SOCKADDR*) &service,     sizeof(service)) == SOCKET_ERROR) {
        printf("1. portnum %d could not be binded\n", portnum);
        closesocket(ListenSocket);
        WSACleanup();
        return false;
      }

       int length = sizeof(service);
       if (getsockname(ListenSocket, (SOCKADDR*)&service, &length) == SOCKET_ERROR) {
        printf("portnum %d could not be got sockname\n", portnum);
        closesocket(ListenSocket);
        WSACleanup();
        return false;
      }

      

      closesocket(ListenSocket);
      WSACleanup();
      return true;

    }



    int main(int argc, char* argv[])
    {
       
        int portnum;
       
        if (argc > 1)
            portnum = atoi(argv[1]);
        else
            portnum = 8013;

        bool ret = CheckPortAvailable(portnum);
        if (ret)
            printf("portnum %d is available.\n", portnum);
        else
            printf("portnum %d is not available.\n", portnum);

        return 0;
    }


    Wednesday, December 17, 2008 9:40 PM