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
Solved

whats wrong with this sockets function?

Posted on 2004-04-22
13
457 Views
Last Modified: 2012-05-04
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
Comment
Question by:meverest
  • 7
  • 3
  • 2
  • +1
13 Comments
 
LVL 37

Author Comment

by:meverest
ID: 10896767
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
 
LVL 6

Expert Comment

by:Mafalda
ID: 10897522
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
 
LVL 6

Expert Comment

by:Mafalda
ID: 10897544
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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 500 total points
ID: 10897810
>>     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
 
LVL 22

Expert Comment

by:grg99
ID: 10898810
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
 
LVL 37

Author Comment

by:meverest
ID: 10905730
>> 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
 
LVL 37

Author Comment

by:meverest
ID: 10906847
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
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 10907039
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
 
LVL 37

Author Comment

by:meverest
ID: 10955313
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
 
LVL 37

Author Comment

by:meverest
ID: 10956727
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
 
LVL 37

Author Comment

by:meverest
ID: 10956738
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
 
LVL 37

Author Comment

by:meverest
ID: 10956741
oh - mafalda, tell me what topic area you watch most?
0
 
LVL 6

Expert Comment

by:Mafalda
ID: 10956928
Hi meverest,
C++
Thanks.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

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

Suggested Solutions

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…
Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
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.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

790 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