#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
//#include <time.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
int listenfd
= 0, connfd = 0, i = 0;
struct
sockaddr_in serv_addr;
listenfd =
socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[1]));
if(bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))
== -1)
{
printf("bind
error\n");
close(listenfd);
return
1;
}
listen(listenfd, 10);
while(1)
{
if((connfd = accept(listenfd,(struct sockaddr *)NULL, NULL))==-1)
{
printf("Invalid
connection\n");
continue;
}
printf("accepted
connection\n");
char
sendBuff[10],op,op1[4],op2[4];
//time_t
ticks;
int a=0,b=0;
//sleep(5);
read(connfd,
sendBuff, sizeof(sendBuff));
op
= sendBuff[0];
//printf("%c",op);
read(connfd,
op1, sizeof(op1));
a
= atoi(op1);
read(connfd,
op2, sizeof(op2));
b
= atoi(op2);
printf("%d
%c %d\n",a,op,b);
//ticks
= time(NULL);
switch(op)
{
case
'+': a = a + b;
break;
case
'-': a = a - b;
break;
case
'*': a = a * b;
break;
case
'/': a = a / b;
break;
case
'%': a = a % b;
}
snprintf(sendBuff,
sizeof(sendBuff), "%d", a);
write(connfd, sendBuff, strlen(sendBuff));
close(connfd);
}
close(listenfd);
return
0;
}
Client Side:
#include
<sys/socket.h>
#include
<sys/types.h>
#include
<netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include
<arpa/inet.h>
int main(int argc, char
*argv[])
{
int sockfd = 0, n = 0;
char recvBuff[1024],op,op1[4],op2[4];
struct sockaddr_in serv_addr;
if(argc != 3)
{
printf("\n Usage: %s <ip of server>
<port>\n",argv[0]);
return 1;
}
memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM,
0)) < 0)
{
printf("\n Error : Could not
create socket \n");
return 1;
}
memset(&serv_addr, '0',
sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[2]));
if(inet_pton(AF_INET, argv[1],
&serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error
occured\n");
return 1;
}
if( connect(sockfd, (struct sockaddr
*)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed
\n");
return 1;
}
printf("Enter operator : ");
scanf("%c", &op);
write(sockfd, &op,1);
printf("Enter operands : ");
scanf("%s%s",op1,op2);
write(sockfd, op1, strlen(op1));
write(sockfd, op2, strlen(op2));
printf("Result : ");
while ( (n = read(sockfd, recvBuff,
sizeof(recvBuff)-1)) > 0)
{
recvBuff[n] = 0;
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs
error\n");
}
printf("\n");
}
if(n < 0)
{
printf("\n Read error \n");
}
return 0;
}
No comments:
Post a Comment
Have some problem with this code? or Request the code you want if you cant find it in Blog Archive.