I'm trying to write a simple TCP client that is able to connect to a server and send and receive messages and commands.
The server is suppose to understand these commands:
AD perform a simple addition
SB perform a simple subtraction
DIV perform a simple division
MUL perform a simple multiplication
IDENT identify the client and itself
QUIT break the current connection and wait for a new one
This is what I got, but there are problems in it. please would anyone have a look and help me out? thank you.
Code:
#include<stdio.h>
#include<String.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<arpa/inet.h>
#define MSGSIZE 64/*size of message buffers*/
#define PORT 3550/*server port number*/
main(int args,char*argv[]){
char sendbuf[MSGSIZE];/*send character buffer*/
char recvbuf[MSGSIZE];/*recive character buffer*/
Struct sockaddr_in server;/*internet domain server*/
int sockket;/*socket descriptor*/
int status;/*socket status*/
int numbytes;/*number of bytes of message*/
if(argc!=2){
printf("Usage:%s<IP Address>\n",argv[0]);
exit(-1);
}
/*Server details */
server.sin_family=AF_INET;
Server.sin_addr.s_addr=inet_addr(argv[1]);
servsr.sin_port=htons(PORT);
Printf("valid IP address,connecting to....%s\n",argv[1]);
/*connet to server*/
if (status=connect(socket,(struct sockaddr*)&server,sizeof (server))<0){
close(socket);
perror("connect");
exit(1);
}
/*recieve message from server*/
if (numbytes=recv(socket,recvbuf,sizeof(recvbuf),0)<0){
perror("recv");
exit(1);
}
/*print response from server*/
recvbuf[numbytes]='\0';
printf("%s\n\n",recvbuf);
/*Being main loop */
for(; ;){
printf("Input a command(AD,SB,DIV,MUL,IDENT,QUIT)\n");
/*get command from user*/
get(sendbuf);
/*send command to server*/
status=send(sock,sendbuf,sizeof(sendbuf),0);
if (status<0){
perror("send");
exit(1);
}
/*recieve message from server*/
numbytes=recv(socket,recvbuf,sizeof(recvbuf),0);
if(states<0){
perror("send");
exit(1);
}
/*Print response frpm server*/
recvbuf[numbytes]='\0';
printf("%s\n\n",recvbuf);
if[strncmp(sendbuf,"QUIT",4)==0){
break;
}
}
close(socket);
printf("connection closed....\n");
return 0;
}