Thread: What's wrong with this code?

  1. #1
    Registered User Finchie_88's Avatar
    Join Date
    Aug 2004
    Posts
    154

    Question What's wrong with this code?

    I can't understand what I'm doing wrong, here is the server code and part of the client code.
    Server:
    Code:
    SOCKET TempSocket = SOCKET_ERROR; // Set the TempSocket to error //
        
        while(TempSocket = SOCKET_ERROR)
        {
              TempSocket = accept(Socket, NULL, NULL);
        }
        Socket = TempSocket;
    Client:
    Code:
    if(connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0)
        {
                  SetConsoleTextAttribute(houtput, BACKGROUND_RED|BACKGROUND_INTENSITY);
                  status = GetLastError();
                  cout << "" << endl;
                  cout << "Failed to establish connection with the server" << endl;
                  cout << "Application error code: " << status << endl;
                  hinput = NULL;
                  houtput = NULL;
                  herror = NULL;
                  Sleep(10000);
                  return;
        }
    Last edited by Finchie_88; 05-24-2005 at 01:10 PM.


  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Do you mean to assign or compare?
    Code:
    while(TempSocket == SOCKET_ERROR)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User Finchie_88's Avatar
    Join Date
    Aug 2004
    Posts
    154
    Yer, but the connection is still refused (error code 10061) by the computer when the client tries to connect. As far as I can tell, there is nothing wrong with the server side. btw before any1 asks, I'm running the server side and then trying to connect, not the other way round.lol


  4. #4
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Could you please post more code, specifically the bind, and listen calls? The client side could also be interesting.

  5. #5
    Registered User Finchie_88's Avatar
    Join Date
    Aug 2004
    Posts
    154
    This is the server code...
    Code:
    // INCLUDES ////////////////////////////////////////////////////////////////////
    #include <cstdlib>
    #include <iostream>
    #include <winsock.h>
    #include <windows.h>
    #include <conio.h>
    
    using namespace std;
    // PROTOTYPES //////////////////////////////////////////////////////////////////
    void serverside();
    WSADATA wsadata;
    SOCKET Socket;
    
    int main(int argc, char *argv[])
    {
        serverside();
        closesocket(Socket);
        WSACleanup();
        return EXIT_SUCCESS;
    }
    
    void serverside()
    {
         char message[1024];
         SOCKADDR_IN SockAddr;
         HANDLE hinput;
         HANDLE houtput;
         HANDLE herror;
         CONSOLE_CURSOR_INFO ConCurInf;
         int status;
         int a, b, c, d;
         
         // MAIN PROGRAM //
         if(status == SetConsoleTitle("Console Chat Program, Server Side"))
        {
                   status = GetLastError();
                  cout << "Application error code: " << status << endl;
                  Sleep(10000);
                  return;
        }
        // SET CONSOLE TEXT ATRIBUTES //
        hinput = GetStdHandle(STD_INPUT_HANDLE);
        houtput = GetStdHandle(STD_OUTPUT_HANDLE);
        herror = GetStdHandle(STD_ERROR_HANDLE);
        if((hinput == NULL)||(houtput == NULL)||(herror == NULL))
        {
                   status = GetLastError();
                   cout << "" << endl;
                   cout << "Failed to establish the handles to the application..." << endl;
                   cout << "Application error code: " << status << endl;
                   hinput = NULL;
                   houtput = NULL;
                   herror = NULL;
                   Sleep(10000);
                   return;
        }
    
        SetConsoleTextAttribute(houtput, FOREGROUND_GREEN);
        
        ConCurInf.dwSize = 10;
        ConCurInf.bVisible = TRUE;
        SetConsoleCursorInfo(houtput,
                             &ConCurInf);
        
        cout << "\t\tConsole Chat Program programmed by Dominic Finch 2005" << endl;
        cout << "" << endl;
        cout << "Establishing the handles to the application..." << endl;
        cout << "Establishing the interface..." << endl;
        cout << "Activating winsock..." << endl;
        if(WSAStartup(MAKEWORD(1,1), &wsadata) != 0)
        {
                   status = WSAGetLastError();
                   SetConsoleTextAttribute(houtput, BACKGROUND_RED|BACKGROUND_INTENSITY);
                   cout << "" << endl;
                   cout << "Failed to activate winsock" << endl;
                   cout << "Application error code: " << status << endl;
                   hinput = NULL;
                   houtput = NULL;
                   herror = NULL;
                   Sleep(10000);
                   return;
        }
        cout << "Establishing socket for a connection..." << endl;
        Socket = socket(AF_INET, SOCK_STREAM, 0);
        if(Socket == INVALID_SOCKET)
        {
                  SetConsoleTextAttribute(houtput, BACKGROUND_RED|BACKGROUND_INTENSITY);
                  status = WSAGetLastError();
                  cout << "" << endl;
                  cout << "Failed to establish the socket" << endl;
                  cout << "Application error code: " << status << endl;
                  hinput = NULL;
                  houtput = NULL;
                  herror = NULL;
                  Sleep(10000);
                  return;
        }
        cout << "Opening port 80 for connection..." << endl;
        
        SockAddr.sin_port = 80; // Setting the port to use //
        SockAddr.sin_family = AF_INET; // Setting the connection type //
        SockAddr.sin_addr.s_addr = INADDR_ANY;
        
        // Now time to bind the socket using the bind() function //
        // As always, chack for errors //
        cout << "Binding the socket..." << endl;
        
        if(bind(Socket,(SOCKADDR *)(&SockAddr), sizeof(SockAddr)) == SOCKET_ERROR)
        {
                 SetConsoleTextAttribute(houtput, FOREGROUND_RED|FOREGROUND_INTENSITY);
                 status = GetLastError();
                 cout << "Error when binding to the socket..." << endl;
                 cout << "Application error code: " << status << endl;
                 hinput = NULL;
                 houtput = NULL;
                 herror = NULL;
                 Sleep(10000);
                 return;
        };
        
        cout << "Listening for a connection..." << endl;
        listen(Socket, 10); // Set the socket to listen //
        
        cout << "Ready to Accept incoming connections..." << endl;
        
        SOCKET TempSocket = SOCKET_ERROR; // Set the TempSocket to -1 (error) //
        
        while(TempSocket == SOCKET_ERROR)
        {
              TempSocket = accept(Socket, NULL, NULL);
        }
        Socket = TempSocket;
        
         system("cls");
         // State that a connection has been made //
        cout << "" << endl;
        cout << "Connection has been made with a client" << endl;
        cout << "Information on the client:" << endl;
        cout << "" << endl;
        
        int ErrVal = SOCKET_ERROR;
        
        for(;;)
        {
               // NEED TO SORT OUT THIS SECTION OF CODE //
               
               // talk to the client in an infinate loop //
               cout << "Server > ";
               cin >> message;
               ErrVal = send(Socket, message, strlen(message)+1, 0); // Recv(); to get info from the client //
               if(ErrVal == -1)
               {
               SetConsoleTextAttribute(houtput, FOREGROUND_RED|FOREGROUND_INTENSITY);
                 status = WSAGetLastError();
                 cout << "Connection terminated at the other end of the connection..." << endl;
                 cout << "Application error code: " << status << endl;
                 hinput = NULL;
                 houtput = NULL;
                 herror = NULL;
                 Sleep(10000);
                 return;
               }
               
               // Recv() message from the client //
               recv(Socket, message, strlen(message)+1, 0); // Recv(); to get info from the client //
               cout << "Client > " << message;
        }
        Sleep(5000);
    };
    the client code...
    Code:
    // INCLUDE FILES ///////////////////////////////////////////////////////////////
    #include <cstdlib>
    #include <iostream>
    #include <winsock.h>
    #include <conio.h>
    
    using namespace std;
    void clientside();
    WSADATA wsadata;
    SOCKET Socket;
    
    int main(int argc, char *argv[])
    {
        clientside();
        closesocket(Socket);
        WSACleanup();
        return EXIT_SUCCESS;
    }
    
    void clientside()
    {
         // LOCAL VARIBLE DECLARATION //
         HANDLE hinput;
         HANDLE houtput;
         HANDLE herror;
         CONSOLE_CURSOR_INFO ConCurInf;
         int status, a, b, c, d;
         char message[1024];
         int ErrVal;
         SOCKADDR_IN SockAddr;
         
         // MAIN PROGRAM //
         if(status == SetConsoleTitle("Console Chat Program, Client Side"))
        {
                   status = GetLastError();
                  cout << "Application error code: " << status << endl;
                  Sleep(10000);
                  return;
        }
        // SET CONSOLE TEXT ATRIBUTES //
        hinput = GetStdHandle(STD_INPUT_HANDLE);
        houtput = GetStdHandle(STD_OUTPUT_HANDLE);
        herror = GetStdHandle(STD_ERROR_HANDLE);
        if((hinput == NULL)||(houtput == NULL)||(herror == NULL))
        {
                   status = GetLastError();
                   cout << "" << endl;
                   cout << "Failed to establish the handles to the application..." << endl;
                   cout << "Application error code: " << status << endl;
                   hinput = NULL;
                   houtput = NULL;
                   herror = NULL;
                   Sleep(10000);
                   return;
        }
        SetConsoleTextAttribute(houtput, FOREGROUND_GREEN);
        
        ConCurInf.dwSize = 10;
        ConCurInf.bVisible = TRUE;
        SetConsoleCursorInfo(houtput,
                             &ConCurInf);
        
        cout << "\t\tConsole Chat Program programmed by Dominic Finch 2005" << endl;
        cout << "" << endl;
        cout << "Establishing the handles to the application..." << endl;
        cout << "Establishing the interface..." << endl;
        cout << "Activating winsock..." << endl;
        if(WSAStartup(MAKEWORD(1,1), &wsadata) != 0)
        {
                   status = GetLastError();
                   SetConsoleTextAttribute(houtput, BACKGROUND_RED|BACKGROUND_INTENSITY);
                   cout << "" << endl;
                   cout << "Failed to activate winsock" << endl;
                   cout << "Application error code: " << status << endl;
                   hinput = NULL;
                   houtput = NULL;
                   herror = NULL;
                   Sleep(10000);
                   return;
        }
        cout << "Establishing socket for a connection..." << endl;
        Socket = socket(AF_INET, SOCK_STREAM, 0);
        if(Socket == INVALID_SOCKET)
        {
                  SetConsoleTextAttribute(houtput, BACKGROUND_RED|BACKGROUND_INTENSITY);
                  status = GetLastError();
                  cout << "" << endl;
                  cout << "Failed to establish the socket" << endl;
                  cout << "Application error code: " << status << endl;
                  hinput = NULL;
                  houtput = NULL;
                  herror = NULL;
                  Sleep(10000);
                  return;
        }
        cout << "Opening port 80 for connection..." << endl;
        
        SockAddr.sin_port = 80; // Setting the port to use //
        SockAddr.sin_family = AF_INET; // Setting the connection type //
        
        // Not the best, but not my of upmost important //
        cout << "Please give an IP to connect to" << endl;
        cout << "IP (1st byte) > ";
        cin >> a;
        cout << "IP (2nd byte) > ";
        cin >> b;
        cout << "IP (3rd byte) > ";
        cin >> c;
        cout << "IP (4th byte) > ";
        cin >> d;
        
        // Check that the IP is possible //
        if((a > 255)||(b > 255)||(c > 255)||(d > 255))
        {
              SetConsoleTextAttribute(houtput, FOREGROUND_RED|FOREGROUND_INTENSITY);
              cout << "One or more of the values entered for the IP are not possible" << endl;
              Sleep(5000);
        }
        
        cout << "Setting client IP to connect to..." << endl;
        // Not the best way to do this, but for now it'll do //
        // REPLACE WITH A FOR LOOP, SO THAT THE IP CAN BE ENTERED AS A STRING OR AN ARRAY //
        SockAddr.sin_addr.S_un.S_un_b.s_b1 = a;
        SockAddr.sin_addr.S_un.S_un_b.s_b2 = b;   // I'll sort this out later //
        SockAddr.sin_addr.S_un.S_un_b.s_b3 = c;
        SockAddr.sin_addr.S_un.S_un_b.s_b4 = d;
        
        // Now time to connect the socket to the server using the connect() function //
        // As always, chack for errors //
        
        if(connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr))  != 0)
        {
                  SetConsoleTextAttribute(houtput, BACKGROUND_RED|BACKGROUND_INTENSITY);
                  status = GetLastError();
                  cout << "" << endl;
                  cout << "Failed to establish connection with the server" << endl;
                  cout << "Application error code: " << status << endl;
                  hinput = NULL;
                  houtput = NULL;
                  herror = NULL;
                  Sleep(10000);
                  return;
        }
        
        cout << "Connection made..." << endl;
        
        // Now time to send something to the server and vicea versa //
        for(;;)
        {
               // SORT THIS OUT //
                       cout << "Client > ";
                      cin >> message;
                      ErrVal = send(Socket, message, strlen(message)+1, 0); // Recv(); to get info from the client //
                      if((ErrVal == 0)||(ErrVal == WSAECONNRESET)||(ErrVal == WSAECONNABORTED))
                      {
                                 SetConsoleTextAttribute(houtput, FOREGROUND_RED|FOREGROUND_INTENSITY);
                                 status = GetLastError();
                                 cout << "Connection terminated at the other end of the connection..." << endl;
                                 cout << "Application error code: " << status << endl;
                                 hinput = NULL;
                                 houtput = NULL;
                                 herror = NULL;
                                 Sleep(10000);
                                 return;
                      }
               
               // Recv() message from the server side //
               recv(Socket, message, strlen(message)+1, 0); // Recv(); to get info from the Server side //
               cout << "Server > " << message << endl;
        }
        Sleep(5000);
    };


  6. #6
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    I think that your problem is that you are not transforming your server IP, at the client, to network order. One must use htons ain Linux OS, refer to Windows documentation, please. Give it a try and let mw know about iy.

  7. #7
    Registered User Finchie_88's Avatar
    Join Date
    Aug 2004
    Posts
    154
    I used the htons function, like you said, but no such luck. I used the netstat function in command prompt to look at the network output of my program, and there isn't anything happening, so I think there must be something else wrong with the server code.


  8. #8
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    I do not know how to tell you, but after a long time trying to find an error, I ran your program as you posted here, i.e., without modifications. I compiled with gcc, and linked against libWs2_32 library. As you are programming for Windows, might I ask if you have firewall enable?

  9. #9
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    I think there must be something else wrong with the server code.
    Code:
    SockAddr.sin_port = 80;
    You need to use htons() there.

    Code:
    recv(Socket, message, strlen(message)+1, 0);
    I'm sure the above code is not what you intended. When you are receiving data into a buffer, you pass the sizeof the buffer itself, not the length of some arbitrary string in the buffer.

  10. #10
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    Yes... these corrections must be made. Without the htons, port 80 (0x0050) will become 20480 (0x5000), if I am not mistaken.

    But the code works "properly", I still think that a firewall could be the problem.

  11. #11
    Registered User Finchie_88's Avatar
    Join Date
    Aug 2004
    Posts
    154
    rite, thats strange, turn out that it wasn't my firewall that was causing the problem, it was my anti-virus, not something that I was expecting, thanks anyway for the tips, much appriciated


Popular pages Recent additions subscribe to a feed

Similar Threads

  1. what is wrong in this simple code
    By vikingcarioca in forum C Programming
    Replies: 4
    Last Post: 04-23-2009, 07:10 AM
  2. what is wrong with this code please
    By korbitz in forum Windows Programming
    Replies: 3
    Last Post: 03-05-2004, 10:11 AM
  3. I cant find what is wrong with this code
    By senegene in forum C Programming
    Replies: 1
    Last Post: 11-12-2002, 06:32 PM
  4. Anyone see what is wrong with this code?
    By Wise1 in forum C Programming
    Replies: 2
    Last Post: 02-13-2002, 02:01 PM
  5. very simple code, please check to see whats wrong
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 10-10-2001, 12:51 AM