?
Solved

whats wrong with this sockets function?

Posted on 2004-04-22
13
Medium Priority
?
460 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
[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
  • 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 2000 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

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!

Question has a verified solution.

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

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

765 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