[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

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

whats wrong with this sockets function?

Hi folks,

this is just supposed to open a tcp connection to remote server:port and return the result of a string written to the remote.  if the server responds on connection (like if it is an smtp server banner etc) then it should also return that string as well:

CString DoComm(CString ServerName, long ServerPort, CString command)
{
      CSocketFile * sockFile = NULL;
      CSocket * sock = NULL;
      CString Response = "Bombed";

      try
      {
            char *BufPtr  = NULL;                // Error message buffer.
            int   MsgLen  = 0;                      // Error message length.
            DWORD Errnum;

//            printf("login1\n");

            CString OutputBuff;

//            char readBuf[256];

            UINT rc;

            CSocket sockCli;

            rc = sockCli.Create( );

            Errnum = GetLastError();

            rc = sockCli.Connect(ServerName, ServerPort);

            sockFile = new CSocketFile(&sockCli);

            char buf[256];

            while( rc=sockFile->Read(buf, 255) )
            {
                  buf[rc] = NULL;
//                  Buf = buf;
                  Response = Response + buf;
                  if ( rc < 255 ) break;
            }

            if( command != "")
            {
                  Response = Response + "\r\n";
                  OutputBuff.Format("%s\r\n", command);

                  sockFile->Write(OutputBuff, OutputBuff.GetLength( ) );

                  char buf[256];

                  while( rc=sockFile->Read(buf, 255) )
                  {
                        buf[rc] = NULL;
//                        Buf = buf;
                        Response = Response + buf;
                        if ( rc < 255 ) break;
                  }
            }

//            Response = Response + "!!!";

            return(Response);
      }
      catch ( ... )
      {
            Response="Encountered Exception"+Response;
            return(Response);
      }
}
0
meverest
Asked:
meverest
  • 7
  • 3
  • 2
  • +1
1 Solution
 
meverestAuthor Commented:
oh, i should have said - it seems to just hang.  i suspect that it is stuck in one of those while() loops, but i can't see why it doesn't break out?

regards,  Mike.
0
 
MafaldaCommented:
Did you try to change to the following ?

rc=sockFile->Read(buf, 255);
while (rc < 255 && rc > 0)
{
  buf[rc] = NULL;
  Response = Response + buf;
  rc=sockFile->Read(buf, 255);
}
 
0
 
MafaldaCommented:
Sorry ... it was a stupid remark ... to much to drink ;o)
But you might have a do-while loop  and exit if the chars read are smaller than 255

do
{
  rc=sockFile->Read(buf, 255);
  buf[rc] = NULL;
  Response = Response + buf;
}
while (rc == 255);

I hope this time I am right ...
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!

 
itsmeandnobodyelseCommented:
>>     while( rc=sockFile->Read(buf, 255) )

sockFile->Read() will wait on a blocking socket as the connection doesn't get disconnected from the server side. However, even if the server disconnects, the while statement will probably hang also as the Read most likely returns SOCKET_ERROR (-1). So it probably hangs here.

If you change to

     while( (rc=sockFile->Read(buf, 255)) > 0 )

it won't hang if server disconnects, but it will wait for messages if the socket is blocking. I would recommend you to use class CSocket rather than CSocketFile - as there is more samples for that - set the socket to non-blocking using function IOCtl(), use Receive() function to read from socket like this:

        // set non-blocking
        sock.IOCtl(FIONBIO, &1);
        while ( true )
        {
              rc = sock.Receive(buf, 255, );
             if (rc == SOCKET_ERROR && WSAGetLastErrror() == WSAEWOULDBLOCK)
             {
                     // check global exit flag
                     if (g_bExit)
                         return;
                    Sleep(10);
                    continue;
             }
             else if (rc == SOCKET_ERROR)
                  return;
             // do something with buf
             ...

        }

Regards, Alex
0
 
grg99Commented:
Look your logic over again....   Do you really want to keep on reading until Read() returns zero?


If it's set to block, it's going to hang waiting for data.

If it's set to not-block, then depending on timing it might or might not find anything to read.

In either case, the code is wrong.

You may want to change to some loop that does a non-blocking read, and times out of that after a few seconds.

BTW I hope this isnt a net snooper.....   :)



0
 
meverestAuthor Commented:
>> BTW I hope this isnt a net snooper.....   :)

well, kind of - it's part of a server status monitor.  it will poll all my servers and make sure that the various services are up and responding as expected.

i suppose it could be used for evil instead of good, but i hadn't intended that! ;-)

itsme & mafalda, i'll try those out and get back.  thanks!

cheers.

0
 
meverestAuthor Commented:
Guys,

after some trial-&-error debugging, i discover that it's actually this like where it hangs:

rc = sockCli.Create( );

it makes me think - do i need to initialise the tcpip[ stack or something - when i used to do this sort of stuff in old ansi C, i had to init the tcpip.  i'm doing nothing like that with this code - should I? how?

thanks & regards,  Mike.
0
 
itsmeandnobodyelseCommented:
I had a similar problem some years ago where i tried to connect to an Oracle database server. Locally all works fine but remote  access didn't work. It turned out that the system had chosen wrong network card where the IP mask didn't match to the IP address of the remote server.

If remote server had a firewall it could prevent using specific ports or nodes. Maybe you should use a sniffer like Microsoft Network Monitor, EthReal, or others  and check what happens. Did you get the error code returned?

Regards, Alex

0
 
meverestAuthor Commented:
Thanks for the suggestion (sorry for my late response - i didn't see the notification for some reason)

That wouldn't be the problem in this case - i have only one interface on both ends, and there's no firewall.

In fact telnets to the relevent ports work fine, just that my program hangs every time :(

cheers,  Mike.
0
 
meverestAuthor Commented:
as i suspected, i had not called WSAStartup()

duh!

i'll split points: most to itsme& and some to mafalda for your useful comments.  thanks.
0
 
meverestAuthor Commented:
that's funny - i thought we could split points from the interface these days.  never mind, points to itsme& - mafalda look for free Q for you.
0
 
meverestAuthor Commented:
oh - mafalda, tell me what topic area you watch most?
0
 
MafaldaCommented:
Hi meverest,
C++
Thanks.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

  • 7
  • 3
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now