Strange errors.

This is a discussion on Strange errors. within the C Programming forums, part of the General Programming Boards category; Hello! This is my first post to this board, however I have been lurkiing and using the search function for ...

  1. #1
    Registered User
    Join Date
    Jan 2003
    Posts
    14

    Strange errors.

    Hello! This is my first post to this board, however I have been lurkiing and using the search function for assistance for some time. I am hoping that someone will be kind enough to help me with a little problem i have been having.

    I am trying to write a 'windows telnet' style application by using pipes for redirection and winsock. I have gone through Beej's tutorial (I heard about it from another thread on this board.) and I basically pilfered my pipe code from MSDN.
    I am using Dev-C++ with the mingw compiler. (at least I think so, its the one that doesn't require cygwin.)

    Here is my problem. If I compile the code below it compiles and runs fine. But if I connect to the server from windows telnet it presents me with the Windows cmd.exe copyright info and will not allow to type in any commands. if I telnet in from my Linux box however it will allow me to type commands, and I receive the responses. The only problem from linux is that I have to hit enter twice for each command.

    I would appreciate any assistance anyone feels like offering very much. I am trying to learn c and this is my first 'real' program.

    Code:
    #include <winsock.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <windows.h>
    
        HANDLE rPipe, rInput;
        HANDLE wPipe, wInput;
        HANDLE wError;
        SECURITY_ATTRIBUTES pipesec;
        STARTUPINFO startInfo;
        PROCESS_INFORMATION pinfo;
        char buffer[1023];
        //char inbuffer[256];
        //char tmpbuffer[256];
        void DiplayError();
    
        BOOL bRet;
        //HANDLE hThread; 
        //HANDLE hThread2;
        //DWORD dwThreadID2;
        //DWORD dwThreadID;
    
        DWORD bytesRead;
        DWORD bytesWrote;
        WSADATA wsda;			// Structure to store information returned from
    					// WSAStartup
    
       char szRepMessage[80];               // Store the reply message
       int iMessageLen;
    
       char szInBuffer[1023];
       int iBufferLen;
    
       int iPort, iAddrLen;
       
       SOCKET sListen, sClient;                    // Our TCP socket handle
       SOCKADDR_IN addr,            // The local interface
                   remote_addr;     // The address of the connecting host   
        
    int main(int argc, int **argv)
    {
    int ret;
    
    
    startup();
       // Receive data
    for (;;) { 
    sendconsole();
    writeconsole();
    }
       printf("Closing client socket & Pipe Handles...");
       closesocket(sClient);
       CloseHandle(rInput);
       CloseHandle(wInput);
       CloseHandle(wPipe);  
       CloseHandle(rPipe);
       printf("OK\n");
    
       return 0;
    }
    
    int writeconsole(){
    int ret;
    
    memset(szInBuffer, 0, sizeof(szInBuffer));
    ret = recv(sClient, szInBuffer, sizeof(szInBuffer), 0);
       if(ret == SOCKET_ERROR)
       {
          DisplayError("Recieve Error!");
          strcpy(szInBuffer, "quit");
          checkcommandline();
       }
    iBufferLen = ret;		// recv() returns the number of bytes read
    checkcommandline();
    WriteFile(wInput, szInBuffer, iBufferLen, &bytesWrote, 0); 
      }
    
    
    int sendconsole(){
    int ret;
    
        for(;;)
            {    DWORD dwRead; BOOL bRet;
            
            memset(buffer, 0, sizeof(buffer));
            bRet = ReadFile(rPipe, buffer, 1023, &bytesRead,0);
            if(bRet==FALSE) { // pipe closed
            DisplayError ("ReadFile"); 
            break;
            }
            if (buffer == NULL){
            DisplayError ("buffer == NULL!");  }
            ret = send(sClient, buffer, strlen(buffer), 0);
                   if(ret == SOCKET_ERROR) {
                   DisplayError ("Send Error!");
                   strcpy(szInBuffer, "quit");
                   checkcommandline();
                   }
            break;  
            }
        }
        
    int DisplayError(char *pszAPI)
       {
           LPVOID lpvMessageBuffer;
           CHAR szPrintBuffer[512];
           DWORD nCharsWritten;
    
           FormatMessage(
                    FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
                    NULL, GetLastError(),
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    (LPTSTR)&lpvMessageBuffer, 0, NULL);
    
           wsprintf(szPrintBuffer,
             "ERROR: API    = %s.\n   error code = %d.\n   message    = %s.\n",
                    pszAPI, GetLastError(), (char *)lpvMessageBuffer);
    
           WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),szPrintBuffer,
                         lstrlen(szPrintBuffer),&nCharsWritten,NULL);
    
           LocalFree(lpvMessageBuffer);
           //ExitProcess(GetLastError());
       }
       
    int checkcommandline()
        {
    if (strstr (szInBuffer, "quit")){
        printf("Closing client socket & Pipe Handles...");
        memset(szInBuffer, 0, sizeof(szInBuffer));
        memset(buffer, 0, sizeof(buffer));
        closesocket(sClient);
        CloseHandle(rInput);
        CloseHandle(wInput);
        CloseHandle(wPipe);  
        CloseHandle(rPipe);
        printf("OK\n");
        startup();}
    
    }
    
    int startup()
        {
        int ret;
       // Get the remote port
        pipesec.nLength = sizeof(SECURITY_ATTRIBUTES);
        pipesec.lpSecurityDescriptor = NULL;
        pipesec.bInheritHandle = TRUE;
        if (!CreatePipe(&rPipe, &wPipe, &pipesec, 0)) 
            MessageBox(NULL,"Error Creating Pipe!",NULL,0);
        if (!CreatePipe(&rInput,&wInput,&pipesec,0))
            MessageBox(NULL,"Error Creating Pipe!",NULL,0);
        startInfo.cb = sizeof(STARTUPINFO);
        GetStartupInfo(&startInfo);
        startInfo.hStdOutput = wPipe;
        startInfo.hStdInput = rInput;
        startInfo.hStdError = wPipe;
        startInfo.dwFlags =  STARTF_USESHOWWINDOW+ STARTF_USESTDHANDLES; 
        startInfo.wShowWindow = SW_HIDE;
        if (!CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, 0, NULL, NULL, &startInfo, &pinfo))
            MessageBox(NULL,"Error Starting CMD.EXE!",NULL,0);
            
            
       iPort = atoi((char *) &"12374");
    
       // Load version 1.1 of Winsock
    
       WSAStartup(MAKEWORD(1,1), &wsda);
    
       // Create a TCP socket
       printf("Creating socket...");
       sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    
       // Error?
       if(sListen == SOCKET_ERROR)
       {
          printf("Error\nCall to socket(AF_INET, SOCK_STREAM, IPPROTO_IP); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("OK\n");
    
       printf("Binding socket to port %d...", iPort);
    
       addr.sin_family = AF_INET;
       addr.sin_port = htons(iPort);
       addr.sin_addr.s_addr = htonl(INADDR_ANY);          // Listen on any interface
    
       ret = bind(sListen, (struct sockaddr *) &addr, sizeof(addr));
    
       // Error?
       if(ret == SOCKET_ERROR)
       {
          printf("Error\nCall to bind(sListen, (struct sockaddr *) &addr, sizeof(addr)); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("OK\n");
    
       printf("Putting socket into listening mode...");
    
       ret = listen(sListen, 10);        // Backlog 10
    
       // Error?
       if(ret == SOCKET_ERROR)
       {
          printf("Error\nCall to listen(sListen, 10); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("OK\n");
    
       printf("Waiting for connections (Press Ctrl-C to exit)...");
    
       iAddrLen = sizeof(remote_addr);
    
       sClient = accept(sListen, (struct sockaddr *) &remote_addr, &iAddrLen);
    
       // Error?
       if(sClient == SOCKET_ERROR)
       {
          printf("Error\nCall to accept(sListen, (struct sockaddr *) remote_addr, sizeof(remote_addr)); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("%s connected\n",
              inet_ntoa(remote_addr.sin_addr));
       closesocket(sListen);
    
    }
    P.S. I hope I used the code tags correctly.

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    The Windows telnet client sends data as type you, not when you press the enter key. This means your application will probably not receive a complete command in one read. You'll need to buffer the incoming data until you know you have received a complete command before you determine which command it is.

    To see what is happening, open an output file stream, and write all your incoming data to it, something like this (this is the contents of said debug file):

    From read 2 bytes:>qu<
    From read 3 bytes:>it\n<

    (\n will actually be a 0xa or 0xd or both)
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User
    Join Date
    Jan 2003
    Posts
    14
    OK, i have modified my code as follows, and now after when I call readfile (right after "perror("5 1/2");" the application stops responding. Is this some kind of default behavior for readfile under certain circumstances? My win32.hlp file mentions overlapped IO. Do I need to use this? Now I'm even more confused.
    Also as a side question, why would the windows telnet send each character, and the linux version buffer? It seems as if it wouldn't make any sense to buffer the responses like linux seems to be doing. For instance what if you were trying to use some sort of menu where 'q' meant quit, would you have to type q-->enter ?

    Code:
    #include <winsock.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <windows.h>
    
        HANDLE rPipe, rInput;
        HANDLE wPipe, wInput;
        HANDLE wError;
        SECURITY_ATTRIBUTES pipesec;
        STARTUPINFO startInfo;
        PROCESS_INFORMATION pinfo;
        char buffer[1023];
        //char inbuffer[256];
        char tmpbuffer[256];
        void DiplayError();
    
        BOOL bRet;
        //HANDLE hThread; 
        //HANDLE hThread2;
        //DWORD dwThreadID2;
        //DWORD dwThreadID;
    
        DWORD bytesRead;
        DWORD bytesWrote;
        WSADATA wsda;			// Structure to store information returned from
    					// WSAStartup
    
       char szRepMessage[80];               // Store the reply message
       int iMessageLen;
    
       char szInBuffer[1023];
       int iBufferLen;
    
       int iPort, iAddrLen;
       
       SOCKET sListen, sClient;                    // Our TCP socket handle
       SOCKADDR_IN addr,            // The local interface
                   remote_addr;     // The address of the connecting host   
        
    int main(int argc, int **argv)
    {
    int ret;
    
    
    startup();
       // Receive data
    for (;;) { 
    sendconsole();
    writeconsole();
    }
       printf("Closing client socket & Pipe Handles...");
       closesocket(sClient);
       CloseHandle(rInput);
       CloseHandle(wInput);
       CloseHandle(wPipe);  
       CloseHandle(rPipe);
       printf("OK\n");
    
       return 0;
    }
    
    int writeconsole(){
    int ret;
    
    memset(szInBuffer, 0, sizeof(szInBuffer));
    ret = recv(sClient, tmpbuffer, sizeof(tmpbuffer), 0);
       if(ret == SOCKET_ERROR)
       {
          DisplayError("Recieve Error!");
          strcpy(szInBuffer, "quit");
          checkcommandline();
       }
        while (!strstr(tmpbuffer, "\n")){
        strcat (szInBuffer, tmpbuffer);
        printf("szInBuffer: %s\n", szInBuffer);
        ret = recv(sClient, tmpbuffer, sizeof(tmpbuffer), 0);
       if(ret == SOCKET_ERROR)
       {
          DisplayError("Recieve Error!");
          strcpy(szInBuffer, "quit");
          checkcommandline();
       }}
       perror("1");
    iBufferLen = strlen (szInBuffer);		// recv() returns the number of bytes read
    perror("2");
    strcat (szInBuffer, "\n\r\0");
    perror("3");
    checkcommandline();
    perror("4");
    WriteFile(wInput, szInBuffer, iBufferLen, &bytesWrote, 0); 
      }
    
    
    int sendconsole(){
    int ret;
    
        for(;;)
            {    DWORD dwRead; BOOL bRet;
            perror("5");
            memset(buffer, 0, sizeof(buffer));
            perror("5 1/2");
            bRet = ReadFile(rPipe, buffer, sizeof(buffer), &bytesRead,NULL);
            perror("6");
            if(bRet==FALSE) { // pipe closed
            perror("7");
            DisplayError ("ReadFile"); 
            break;
            }
            if (buffer == NULL){
            perror("8");
            DisplayError ("buffer == NULL!");  }
            ret = send(sClient, buffer, strlen(buffer), 0);
            perror("9");
                   if(ret == SOCKET_ERROR) {
                   DisplayError ("Send Error!");
                   strcpy(szInBuffer, "quit");
                   checkcommandline();
                   }
            break;  
            }
        }
        
    int DisplayError(char *pszAPI)
       {
           LPVOID lpvMessageBuffer;
           CHAR szPrintBuffer[512];
           DWORD nCharsWritten;
    
           FormatMessage(
                    FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
                    NULL, GetLastError(),
                    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
                    (LPTSTR)&lpvMessageBuffer, 0, NULL);
    
           wsprintf(szPrintBuffer,
             "ERROR: API    = %s.\n   error code = %d.\n   message    = %s.\n",
                    pszAPI, GetLastError(), (char *)lpvMessageBuffer);
    
           WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE),szPrintBuffer,
                         lstrlen(szPrintBuffer),&nCharsWritten,NULL);
    
           LocalFree(lpvMessageBuffer);
           //ExitProcess(GetLastError());
       }
       
    int checkcommandline()
        {
    if (strstr (szInBuffer, "quit")){
        printf("Closing client socket & Pipe Handles...");
        memset(szInBuffer, 0, sizeof(szInBuffer));
        memset(buffer, 0, sizeof(buffer));
        closesocket(sClient);
        CloseHandle(rInput);
        CloseHandle(wInput);
        CloseHandle(wPipe);  
        CloseHandle(rPipe);
        printf("OK\n");
        startup();}
    
    }
    
    int startup()
        {
        int ret;
       // Get the remote port
        pipesec.nLength = sizeof(SECURITY_ATTRIBUTES);
        pipesec.lpSecurityDescriptor = NULL;
        pipesec.bInheritHandle = TRUE;
        if (!CreatePipe(&rPipe, &wPipe, &pipesec, 0)) 
            MessageBox(NULL,"Error Creating Pipe!",NULL,0);
        if (!CreatePipe(&rInput,&wInput,&pipesec,0))
            MessageBox(NULL,"Error Creating Pipe!",NULL,0);
        startInfo.cb = sizeof(STARTUPINFO);
        GetStartupInfo(&startInfo);
        startInfo.hStdOutput = wPipe;
        startInfo.hStdInput = rInput;
        startInfo.hStdError = wPipe;
        startInfo.dwFlags =  STARTF_USESHOWWINDOW+ STARTF_USESTDHANDLES; 
        startInfo.wShowWindow = SW_HIDE;
        if (!CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, 0, NULL, NULL, &startInfo, &pinfo))
            MessageBox(NULL,"Error Starting CMD.EXE!",NULL,0);
            
            
       iPort = atoi((char *) &"12374");
    
       // Load version 1.1 of Winsock
    
       WSAStartup(MAKEWORD(1,1), &wsda);
    
       // Create a TCP socket
       printf("Creating socket...");
       sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
    
       // Error?
       if(sListen == SOCKET_ERROR)
       {
          printf("Error\nCall to socket(AF_INET, SOCK_STREAM, IPPROTO_IP); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("OK\n");
    
       printf("Binding socket to port %d...", iPort);
    
       addr.sin_family = AF_INET;
       addr.sin_port = htons(iPort);
       addr.sin_addr.s_addr = htonl(INADDR_ANY);          // Listen on any interface
    
       ret = bind(sListen, (struct sockaddr *) &addr, sizeof(addr));
    
       // Error?
       if(ret == SOCKET_ERROR)
       {
          printf("Error\nCall to bind(sListen, (struct sockaddr *) &addr, sizeof(addr)); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("OK\n");
    
       printf("Putting socket into listening mode...");
    
       ret = listen(sListen, 10);        // Backlog 10
    
       // Error?
       if(ret == SOCKET_ERROR)
       {
          printf("Error\nCall to listen(sListen, 10); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("OK\n");
    
       printf("Waiting for connections (Press Ctrl-C to exit)...");
    
       iAddrLen = sizeof(remote_addr);
    
       sClient = accept(sListen, (struct sockaddr *) &remote_addr, &iAddrLen);
    
       // Error?
       if(sClient == SOCKET_ERROR)
       {
          printf("Error\nCall to accept(sListen, (struct sockaddr *) remote_addr, sizeof(remote_addr)); failed with:\n%d\n", WSAGetLastError());
          exit(1);
       }
    
       printf("%s connected\n",
              inet_ntoa(remote_addr.sin_addr));
       closesocket(sListen);
    
    }
    Last edited by emonk; 01-22-2003 at 12:54 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sneaky little linker errors...
    By Tozar in forum C++ Programming
    Replies: 8
    Last Post: 10-25-2006, 06:40 AM
  2. Errors with header files in OpenGL using VisualC++
    By wile_spice in forum Game Programming
    Replies: 3
    Last Post: 06-22-2006, 09:56 AM
  3. strange errors
    By duvernais28 in forum C Programming
    Replies: 9
    Last Post: 02-19-2005, 09:40 AM
  4. strange errors?
    By egomaster69 in forum C Programming
    Replies: 6
    Last Post: 12-21-2004, 06:13 PM
  5. help with strange errors
    By rockdj in forum C++ Programming
    Replies: 4
    Last Post: 07-27-2004, 12:42 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21