Thread: Server sending a message

  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    16

    Server sending a message

    Code:
    #include <stdio.h>      /* for printf() and fprintf() */
    #include <sys/socket.h> /* for recv() and send() */
    #include <unistd.h>     /* for close() */
    
    #define RCVBUFSIZE 32   /* Size of receive buffer */
    
    void DieWithError(char *errorMessage);  /* Error handling function */
    
    void HandleTCPClient(int clntSocket)
    {
        char echoBuffer[RCVBUFSIZE];        /* Buffer for echo string */
        int recvMsgSize;                    /* Size of received message */
    int bytesRcvd, totalBytesRcvd; 
     unsigned int echoStringLen; 
     int sock;
    
        /* Receive message from client */
        if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
            DieWithError("recv() failed");
    
    
       /* Receive the same string back from the server */
        totalBytesRcvd = 0;
        printf("Received: ");                /* Setup to print the echoed string */
        while (totalBytesRcvd < echoStringLen)
        {
            /* Receive up to the buffer size (minus 1 to leave space for
               a null terminator) bytes from the sender */
            if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
                DieWithError("recv() failed or connection closed prematurely");
            totalBytesRcvd += bytesRcvd;   /* Keep tally of total bytes */
            echoBuffer[bytesRcvd] = '\0';  /* Terminate the string! */
            printf("%s", echoBuffer);      /* Print the echo buffer */
        }
    
    
      
          if(echoBuffer == "1")
          {
          echoBuffer = "One";
          recvMsgSize = 3;
          }
       
    
        /* Send received string and receive again until end of transmission */
        while (recvMsgSize > 0)      /* zero indicates end of transmission */
        {
            /* Echo message back to client */
            if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
                DieWithError("send() failed");
    
            /* See if there is more data to receive */
            if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
                DieWithError("recv() failed");
    
       }
    
        close(clntSocket);    /* Close client socket */
    }

    if(echoBuffer == "1")
    {
    echoBuffer = "One";
    recvMsgSize = 3;
    }


    /* Send received string and receive again until end of transmission */
    while (recvMsgSize > 0) /* zero indicates end of transmission */
    {
    /* Echo message back to client */
    if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
    DieWithError("send() failed");

    /* See if there is more data to receive */
    if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
    DieWithError("recv() failed");

    }

    Hello,

    I am trying to work out how to change a char string echoBuffer on a client server program. This would be on the server side. What would happen is the server gets a numerical value 1, 2, 3 then changes it to its text representative one, two, three etc.. then sends it back to client so echoBuffer is the number value then in a series of if statements would be changed yet still remaining a char of course.

    Can anyone give me some pointers on how to do the above in c. The main language I've learn't is java but I'm trying to learn c at the moment. I've looked round google and have spent a good few hours trying to work it out.

    Thanks.

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    What error messages is your DieWithError() function generating? Or does it simply spit out whatever you put into it?

  3. #3
    Registered User
    Join Date
    Dec 2008
    Posts
    16
    ‘HandleTCPClient’:
    HandleTCPClient.c:38: warning: assignment makes integer from pointer without a cast

    error: expected expression before ‘]’ token

    recv() failed or connection closed prematurely: Bad file descriptor

    HandleTCPClient.c:39: error: incompatible types in assignment

    are some of the errors Ive been getting. Been trying a few different things. The last ones been the most common.

    Thanks.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Moved to Networking/Device Communication forum.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > if(echoBuffer == "1")
    > echoBuffer = "One";
    Look up strcmp() and strcpy() respectively.


    > if ((bytesRcvd = recv(sock, echoBuffer, RCVBUFSIZE - 1, 0)) <= 0)
    I see no sock = between where you declare the variable, and where you use it.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  6. #6
    Registered User
    Join Date
    Dec 2008
    Posts
    16
    Sorry, I should have included the TCPEchoServer and TCPEchoClient classes which deal with creating the socket.


    TCPEchoServer is bellow:

    Code:
    #include <stdio.h>      /* for printf() and fprintf() */
    #include <sys/socket.h> /* for socket(), bind(), and connect() */
    #include <arpa/inet.h>  /* for sockaddr_in and inet_ntoa() */
    #include <stdlib.h>     /* for atoi() and exit() */
    #include <string.h>     /* for memset() */
    #include <unistd.h>     /* for close() */
    
    #define MAXPENDING 5    /* Maximum outstanding connection requests */
    
    void DieWithError(char *errorMessage);  /* Error handling function */
    void HandleTCPClient(int clntSocket);   /* TCP client handling function */
    
    int main(int argc, char *argv[])
    {
        int servSock;                    /* Socket descriptor for server */
        int clntSock;                    /* Socket descriptor for client */
        struct sockaddr_in echoServAddr; /* Local address */
        struct sockaddr_in echoClntAddr; /* Client address */
        unsigned short echoServPort;     /* Server port */
        unsigned int clntLen;            /* Length of client address data structure */
    
       
    
        echoServPort = 9165;  /* First arg:  local port */
    
        /* Create socket for incoming connections */
        if ((servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
            DieWithError("socket() failed");
          
        /* Construct local address structure */
        memset(&echoServAddr, 0, sizeof(echoServAddr));   /* Zero out structure */
        echoServAddr.sin_family = AF_INET;                /* Internet address family */
        echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); /* Any incoming interface */
        echoServAddr.sin_port = htons(echoServPort);      /* Local port */
    
        /* Bind to the local address */
        if (bind(servSock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
            DieWithError("bind() failed");
    
        /* Mark the socket so it will listen for incoming connections */
        if (listen(servSock, MAXPENDING) < 0)
            DieWithError("listen() failed");
    
        for (;;) /* Run forever */
        {
            /* Set the size of the in-out parameter */
            clntLen = sizeof(echoClntAddr);
    
            /* Wait for a client to connect */
            if ((clntSock = accept(servSock, (struct sockaddr *) &echoClntAddr, 
                                   &clntLen)) < 0)
                DieWithError("accept() failed");
    
            /* clntSock is connected to a client! */
    
            printf("Handling client %s\n", inet_ntoa(echoClntAddr.sin_addr));
    
            HandleTCPClient(clntSock);
        }
        /* NOT REACHED */
    }


    TCPEchoClient

    Code:
    #include <stdio.h>      /* for printf() and fprintf() */
    #include <sys/socket.h> /* for socket(), connect(), send(), and recv() */
    #include <arpa/inet.h>  /* for sockaddr_in and inet_addr() */
    #include <stdlib.h>     /* for atoi() and exit() */
    #include <string.h>     /* for memset() */
    #include <unistd.h>     /* for close() */
    
    #define RCVBUFSIZE 32   /* Size of receive buffer */
    
    void DieWithError(char *errorMessage);  /* Error handling function */
    
    int main(int argc, char *argv[])
    {
        int sock;                        /* Socket descriptor */
        struct sockaddr_in echoServAddr; /* Echo server address */
        short echoServPort;     /* Echo server port */
        char *servIP;                    /* Server IP address (dotted quad) */
        char *echoString;                /* String to send to echo server */
        char echoBuffer[RCVBUFSIZE];     /* Buffer for echo string */
        unsigned int echoStringLen;      /* Length of string to echo */
        int bytesRcvd, totalBytesRcvd;   /* Bytes read in single recv() 
                                            and total bytes read */
    
    
        if ((argc < 2) || (argc > 3))    /* Test for correct number of arguments */
        {
           fprintf(stderr, "Usage: %s <Server IP> <Echo Word> [<Echo Port>]\n",
                   argv[0]);
           exit(1);
        }
        argv[4] = argv[3];
        servIP = argv[1];             /* First arg: server IP address (dotted quad) */
        echoString = argv[2];         /* Second arg: string to echo */
    
       
    
    
        if (argc == 4)
            echoServPort = 9165; /* Use given port, if any */
        else
            echoServPort = 9165;  /* 7 is the well-known port for the echo service */
    
    
        /* Create a reliable, stream socket using TCP */
        if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
            DieWithError("socket() failed");
    
        /* Construct the server address structure */
        memset(&echoServAddr, 0, sizeof(echoServAddr));     /* Zero out structure */
        echoServAddr.sin_family      = AF_INET;             /* Internet address family */
        echoServAddr.sin_addr.s_addr = inet_addr(servIP);   /* Server IP address */
        echoServAddr.sin_port        = htons(echoServPort); /* Server port */
    
        /* Establish the connection to the echo server */
        if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
            DieWithError("connect() failed");
    
        echoStringLen = strlen(echoString);          /* Determine input length */
    
        /* Send the string to the server */
        if (send(sock, echoString, echoStringLen, 0) != echoStringLen)
            DieWithError("send() sent a different number of bytes than expected");
    
        /* Receive the same string back from the server */
        totalBytesRcvd = 0;
        printf("Received: ");                /* Setup to print the echoed string */
        while (totalBytesRcvd < echoStringLen)
        {
            /* Receive up to the buffer size (minus 1 to leave space for
               a null terminator) bytes from the sender */
            if ((bytesRcvd = recv(sock, echoBuffer, 3 - 1, 0)) <= 0)
                DieWithError("recv() failed or connection closed prematurely");
            totalBytesRcvd += bytesRcvd;   /* Keep tally of total bytes */
            echoBuffer[bytesRcvd] = '\0';  /* Terminate the string! */
            printf("%s", echoBuffer);      /* Print the echo buffer */
        }
    
        printf("\n");    /* Print a final linefeed */
    
        close(sock);
        exit(0);
    }

    Ive changed the if statement to this:

    Code:
        if(strcmp(echoBuffer, "1") == 0)
        {
            echoBuffer = "One";
            recvMsgSize = 3;
        }
    I think the problem is I'm trying to put the word "One" into a character string and there different types. The Error on the above code is:

    HandleTCPClient.c: In function ‘HandleTCPClient’:
    HandleTCPClient.c:40: error: subscripted value is neither array nor pointer

    Line 39 = echoBuffer = "One";
    Line 40 = recvMsgSize = 3;

    Thanks for any help. I've just started leaning see and having done java for the past few years I've got to get used to the syntax.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    The error message is probably a bit confusing, but:
    Code:
            echoBuffer = "One";
    will not work because echoBuffer is an array - regular assignment doesn't work for arrays in C. As suggested before, look into strcpy().

    My guess would be that you are not very familiar with C, and you are just modifying some example code you found on the web. It may be a good idea to start with something a bit more basic.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Registered User
    Join Date
    Dec 2008
    Posts
    16
    Yeah, this is just stuff we've been given to learn how tcp/ip works using wireshark as part of of the ethical hacking part of our computer forensic course. Its not assessed work. I've been brushing up on c but haven't a lot of time with it been the final year.

    I've changed the problem code as bellow so it passes values to memory locations which compiles fine. The problem now is, client and server are both getting a receive error code. I've changed the code so number was "1" instead of "one" to see if that affected the codes send function due to size differences with "recvMsgSize"

    (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)

    Code:
         char number[RCVBUFSIZE];
         strcpy(number, "one");
       
        if(strcmp(echoBuffer, "1") == 0)
        { 
            strcpy(echoBuffer, number);
        }

    Handling client 127.0.0.1
    recv() failed or connection closed prematurely: Bad file descriptor

    ./EchoClient 127.0.0.1 1
    recv() failed or connection closed prematurely: Success


    ./EchoClient 127.0.0.1 1 executes programming sending the 1 value to the server. Server changes that value to "one" and sends it back.

    Thanks for any help. Spent all day trying to work this out.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sending data - line by line?
    By tuckker in forum C Programming
    Replies: 0
    Last Post: 02-21-2009, 09:31 PM
  2. Problem in message handling VC++
    By 02mca31 in forum Windows Programming
    Replies: 5
    Last Post: 01-16-2009, 09:22 PM
  3. Replies: 2
    Last Post: 07-24-2008, 06:05 AM
  4. Replies: 2
    Last Post: 11-23-2007, 02:10 AM
  5. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 03:25 AM