Thread: Server sending a message

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    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.

  2. #2
    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.

  3. #3
    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