Solved

whats wrong with this sockets function?

Posted on 2004-04-22
13
451 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
 
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
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

IT, Stop Being Called Into Every Meeting

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!

Join & Write a Comment

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. …
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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.

757 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

20 Experts available now in Live!

Get 1:1 Help Now