Solved

Winsock programming.

Posted on 2002-03-05
6
530 Views
Last Modified: 2007-12-19
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
Comment
Question by:gadio
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 32

Expert Comment

by:jhance
ID: 6843951
"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
 
LVL 30

Expert Comment

by:Axter
ID: 6844014
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
 
LVL 6

Author Comment

by:gadio
ID: 6846516
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
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!

 
LVL 4

Expert Comment

by:havman56
ID: 6980895
this is my server code if it is useful use it!
it works fine
0
 
LVL 4

Accepted Solution

by:
havman56 earned 100 total points
ID: 6980900
/********************************************************************
 * 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
 
LVL 11

Expert Comment

by:griessh
ID: 7007085
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question