Solved

Winsock programming.

Posted on 2002-03-05
6
522 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
6 Comments
 
LVL 32

Expert Comment

by:jhance
Comment Utility
"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
Comment Utility
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
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 4

Expert Comment

by:havman56
Comment Utility
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
Comment Utility
/********************************************************************
 * 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
Comment Utility
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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
What is C++ STL?: STL stands for Standard Template Library and is a part of standard C++ libraries. It contains many useful data structures (containers) and algorithms, which can spare you a lot of the time. Today we will look at the STL Vector. …
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now