Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 532
  • Last Modified:

Winsock programming.

I am trying to do a simple thing - opening a socket. For some reason I keep getting 10065 (WSA connection refused).
Note that waitForASocketEvent() returns immidietly with indication for a WSA event.
It must be a simple problem. Here is the code:

     if(m_hSocket != INVALID_SOCKET)
          return true;

     // create a TCP/IP socket
     if ( (m_hSocket = ::socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
     {
          displaySocketError("Allocating socket failed.");
          return false;
     }

     long buf = 32768;
    int res;
    res = setsockopt (m_hSocket, SOL_SOCKET, SO_RCVBUF, (LPCSTR)&buf, sizeof(buf));
    res = setsockopt (m_hSocket, SOL_SOCKET, SO_SNDBUF, (LPCSTR)&buf, sizeof(buf));

//--------------------
      if(m_hSocket == INVALID_SOCKET)
          return true;

     ResetEvent(m_hSocketEvent);
     WSAEventSelect(m_hSocket, m_hSocketEvent, FD_CONNECT);

     // request for connection.

     int nSizeOfSource_sin = sizeof(source_sin);
     if (::connect(m_hSocket , (PSOCKADDR)&source_sin , nSizeOfSource_sin) == SOCKET_ERROR)
     {
          int err = WSAGetLastError();
          if(err != WSAEWOULDBLOCK && err != WSAEINVAL && err != WSAEALREADY)
               return false;
     }


     // wait for the unit to accept the connect request.
     int wait_res = waitForASocketEvent();
     //at this point call to terminate or connection has established

     // someone call to terminate.
     if(wait_res == res_ReleaseAllThreads)
     {
          //setContinue(false);
          return false;
     }
     else if(wait_res == res_Timeout)
          return false;


     //check for errors
     WSANETWORKEVENTS networkEvents;
     ::WSAEnumNetworkEvents(m_hSocket , m_hSocketEvent , &networkEvents);
     if(networkEvents.lNetworkEvents == FD_CONNECT)
     {    
          int err = networkEvents.iErrorCode[FD_CONNECT_BIT];
          if(err == WSAECONNREFUSED || err == WSAETIMEDOUT )
//************ Here is the fail ********//
               return false;
     }

     return true;


Also :
inline int WinSocket::waitForASocketEvent()
{
     int result = 0;
     HANDLE h[2];
     h[0] = m_hSocketEvent;
     h[1] = m_hReleaseAllThreads;

     DWORD lockVal = ::WSAWaitForMultipleEvents(2, h, false, INFINITE, false );

     switch (lockVal)
     {
     case WSA_WAIT_TIMEOUT/*WAIT_TIMEOUT*/:
          result = res_Timeout;
          break;

     case WSA_WAIT_EVENT_0/*WAIT_OBJECT_0*/:
          result = res_SocketEvent;
          break;

     case WSA_WAIT_EVENT_0+1/*WAIT_OBJECT_0+1*/:
          result = res_ReleaseAllThreads; // all threads are to be released (someone call to terminate).
          break;

     default :
          result = 0;
          break;
     }
     return result;
}
0
gadio
Asked:
gadio
1 Solution
 
jhanceCommented:
"connection refused" is a problem coming back from the host being connected to.  Is there a reason why you don't believe what this error is telling you?  Have you verified that you can manually connect to this host/port using telnet?

Something like:

TELNET 192.168.0.10 2345

Syntax: TELNET <IP ADDRESS OR HOSTNAME> [PORT #]

See what happens.  Be sure your application is actually connecting to the correct port #.
0
 
AxterCommented:
Did you make a call to WSAStartup() function before making your socket calls?

You need to do that or your socket functions will fail.

Example:
     WORD    wVersion = MAKEWORD( 1, 1 );
     WSADATA wsaData;
     if (WSAStartup(wVersion, &wsaData)) m_InitiateGood=false;
     else m_InitiateGood = true;


Also once your done with your socket functions you should call WSACleanup
0
 
gadioAuthor Commented:
jhance, yes - I have also the server side, and just to be sure - I did use telnet to check that the port is listening. That is why I issued this Q.
Axter - I have used the WSAStartup() during the initialization stage. I will however double check that its all there.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
havman56Commented:
this is my server code if it is useful use it!
it works fine
0
 
havman56Commented:
/********************************************************************
 * File                        : Dserver2.cpp
 *
 * Description             : Extremely simple,
 *                    Works in conjunction with DClient2.cpp.
 *
 * Action performed :  The program sets itself up as a server using the UDP
 *                     protoocl. It waits for data from a client, displays
 *                     the incoming data, sends a message back to the client
 *                     and then exits.
 *
 * Actons needed    : Pass the port number that the server should bind() to
 *                                on the command line. Any port number not already in use
 *                                can be specified.
 *
 *                    Example: DServer 2000
 *
 * library                :  Compile and link with wsock32.lib
 *
 *                                
 *
 * Functions used      : DatagramServer()
 * Revision History      : none
 *
 *
 * Author           : micro Mangal
 * email            : micro_mangal@yahoo.com
 *********************************************************************/



/*
 * header files needed for interacting with TCP IP stack of windows
 */


#include <stdio.h>
#include <winsock.h>
#include<certexit.h>

/* datagram client function  */
void DatagramServer(short nPort);

/* Helper macro for displaying errors */
#define PRINTERROR(s)      \
            fprintf(stderr,"\n%: %d\n", s, WSAGetLastError())


      char szBuf[256];

      void GetConnectedClients();
void ShutdownServer();

void main(int argc, char **argv)
{
      WORD wVersionRequested = MAKEWORD(1,1);
      WSADATA wsaData;
      int nRet;
      short nPort;

      /*
       *Check for port argument
       */
      if (argc != 2)
      {
            fprintf(stderr,"\nSyntax: dserver PortNumber\n");
            return;
      }

      nPort = atoi(argv[1]);
      
      /*
       * Initialize WinSock and check version
       */
      nRet = WSAStartup(wVersionRequested, &wsaData);
      if (wsaData.wVersion != wVersionRequested)
      {      
            fprintf(stderr,"\n Wrong version\n");
            return;
      }

      /*
       * Do all the stuff a datagram server does
       */
      DatagramServer(nPort);
      
      /*
       * Release WinSock
       */
      WSACleanup();
}

////////////////////////////////////////////////////////////

void DatagramServer(short nPort)
{
      /*
       * Create a UDP/IP datagram socket
       */
      SOCKET theSocket;

      theSocket = socket(AF_INET,            // Address family
                                 SOCK_DGRAM,  // Socket type
                                 IPPROTO_UDP);// Protocol
      if (theSocket == INVALID_SOCKET)
      {
            PRINTERROR("socket()");
            return;
      }

      
      /*
       * Fill in the address structure
       */
      SOCKADDR_IN saServer;

      saServer.sin_family = AF_INET;
      saServer.sin_addr.s_addr = INADDR_ANY; // Let WinSock assign address
      saServer.sin_port = htons(nPort);         // Use port passed from user


      /*
       * bind the name to the socket
       */
      int nRet;

      nRet = bind(theSocket,                        // Socket descriptor
                        (LPSOCKADDR)&saServer,  // Address to bind to
                        sizeof(struct sockaddr)      // Size of address
                        );
      if (nRet == SOCKET_ERROR)
      {
            PRINTERROR("bind()");
            closesocket(theSocket);
            return;
      }


      /*
       * This isn't normally done or required, but in this
       * example we're printing out where the server is waiting
       * so that you can connect the example client.
       */
      int nLen;
      nLen = sizeof(SOCKADDR);


      nRet = gethostname(szBuf, sizeof(szBuf));
      if (nRet == SOCKET_ERROR)
      {
            PRINTERROR("gethostname()");
            closesocket(theSocket);
            return;
      }

      /*
       * Show the server name and port number
       */
      printf("\nServer named %s waiting on port %d\n",
                  szBuf, nPort);
                  

      /*
       * Wait for data from the client
       */
      SOCKADDR_IN saClient;

      memset(szBuf, 0, sizeof(szBuf));
      nRet = recvfrom(theSocket,                        // Bound socket
                              szBuf,                              // Receive buffer
                              sizeof(szBuf),                  // Size of buffer in bytes
                              0,                                    // Flags
                              (LPSOCKADDR)&saClient,      // Buffer to receive client address
                              &nLen);                              // Length of client address buffer

      /*
       * Show that we've received some data
       */
      printf("\ncommand recived : %s", szBuf);


      

      

            
            sendto(theSocket,                              // Bound socket
               szBuf,                                          // Send buffer
               strlen(szBuf),                              // Length of data to be sent
               0,                                                // Flags
               (LPSOCKADDR)&saClient,                  // Address to send data to
               nLen);                                          // Length of address
      
      /*
       * Normally a server continues to run so that
       * it is available to other clients. In this
       * example, we exit as soon as one transaction
       * has taken place.
       */
      closesocket(theSocket);
      return;
}



0
 
griesshCommented:
Dear gadio

I think you forgot this question. I will ask Community Support to close it unless you finalize it within 7 days. You can always request to keep this question open. But remember, experts can only help you if you provide feedback to their questions.
Unless there is objection or further activity,  I will suggest to accept

     "havman56"

comment(s) as an answer.

If you think your question was not answered at all, you can post a request in Community support (please include this link) to refund your points. The link to the Community Support area is: http://www.experts-exchange.com/commspt/

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!
======
Werner
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now