Client Source

This client is farly basic. It just keeps sending until exit is typoed in. You can can get the source from Client/client.c


#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <netinet/in.h>
#include <limits.h>
#include <netdb.h>
#include <arpa/inet.h>

char G_PROMPT[]=">"; /*The prompt used*/

struct MESSAGE
{
    char mes1[100];
};

struct sockaddr_in serverAddr;

/*Sets up the connection
returns 0 if successfull else -1*/
int con(void);

/*Fills a struct with the message to be sent etc*/
struct MESSAGE* getMessage(void);

int send_r(int sockdesc, char* pmessage); /*Send the message pointed out to server*/

int main (void)
{
    int user_error=0,sockdesc = 0;
    struct MESSAGE* pmes;

/*Set up connection*/
    if ( (sockdesc = con())==-1) {
        fprintf (stderr, "Failed to connect to Server!\n");
        return -1;
    }

do {
    pmes = getMessage();
    user_error = send_r(sockdesc, pmes->mes1);
    } while ( user_error == 0);

printf("Server has closed the connection, now exiting.\n");
return 0;
}

int con(void)
{
    char ip_address[13]="127.0.0.1";
    int portNumber = 10001;
    int aSocket, errorcode;

    aSocket = socket( AF_INET, SOCK_STREAM, 6);

/* Thing required for bind */
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(portNumber);
    serverAddr.sin_addr.s_addr = inet_addr(ip_address);
    bzero(&(serverAddr.sin_zero),8);
   

    if (errorcode = connect( aSocket, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr )) == 0)
    return aSocket;
    else
    return -1;
    }

int send_r(int sockdesc, char* mes1)
{
    int errorcode, bytesSent, bytesRecv, messageLen;
    char send_buffer[100];
    char recv_buffer[100];

    messageLen = sizeof(char[100]);
   

    strcpy(send_buffer,mes1); /*Put the message to be sent in send buffer*/

/*Send MESSAGE */
    bytesSent = send(sockdesc, send_buffer, messageLen,0);
    bzero(send_buffer,messageLen);

/*Recive Message*/
    bytesRecv = recv(sockdesc, recv_buffer, messageLen,0);
    printf("%s\n",recv_buffer);

/*Check if Server closes connection, server returns "closed" before closeing.
    Currectly it does that when "exit" is sent to server*/
    if ( strncmp(recv_buffer,"closed",6)==0)
    return -1;
    else
    return 0;
   }

struct MESSAGE* getMessage(void)
{

struct MESSAGE MES;
struct MESSAGE* pm = &MES;
printf("%s",G_PROMPT);
fflush(NULL);
scanf("%s",&MES.mes1);

return pm;
}



















 

Last updated 1999-05-02 by Christian Holm