SERVER CODE
Save It With server.c
/*
* Usage : ./server <SERVER IP ID> <PORT NU.>
* Use port number between 5000 to 65535
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
main(int argc,char **argv)
{
int sfd, nfd, portno;
char a[25];
char reply[100];
struct sockaddr_in v,v1;
int n;
int size=0;
FILE *in=NULL;
char server[256],client[256];
in=popen("id -n -u", "r");
fgets(server,100, in);
strtok(server, "\n");
//printf("%s",server);
//socklen_t n;
// First call to socket() function /
sfd = socket(AF_INET, SOCK_STREAM, 0);
if(sfd<0)
{
perror("socket");
}
v.sin_family = AF_INET;
v.sin_addr.s_addr =inet_addr(atoi(argv[1])); /////server ip add
v.sin_port = htons(atoi(argv[2])); ///// port num
bind(sfd, (struct sockaddr *) &v, sizeof(v));
perror("bind");
listen(sfd,1);
perror("listen");
n=sizeof(v1);
printf("n=%d\n",n);
int cnt = 0;
nfd = accept(sfd, (struct sockaddr *) &v1, &n);
perror("accept");
while(1)
{
if(cnt==0) //if condition transfer user name on client side.
{
read(nfd,a,sizeof(a));
strcpy(client,a);
bzero(a,sizeof(a));
cnt++;
send(nfd,server,strlen(server)+1,0);
}
else // else condition use for normal cheting.
{
bzero(a,sizeof(a));
recv(nfd,a,sizeof(a),0);
if(a[0]=='q')
{
close(nfd);
break;
}
printf("%s-->%s",client,a);
sleep(1);
printf("%s:",server);
bzero(reply,sizeof(reply));
fgets(reply,sizeof(reply),stdin);
send(nfd,reply,strlen(reply)+1,0);
}
}
}
CLIENT CODE
Save It With client.c
/*
* Usage : ./client <SERVER IP ID> <PORT NU.>
* Use port number between 5000 to 65535
*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
main(int argc,char **argv)
{
int sfd, nfd, portno, clilen;
char a[25],b[25];
struct sockaddr_in v;
int n;
int size=0;
FILE *in=NULL;
char client[256],server[256];
in=popen("id -n -u", "r");
fgets(client,100, in);
strtok(client, "\n");
// First call to socket() function /
sfd = socket(AF_INET, SOCK_STREAM, 0);
v.sin_family = AF_INET;
v.sin_addr.s_addr =inet_addr(atoi(argv[1]));
v.sin_port = htons(atoi(argv[2]));
bind(sfd, (struct sockaddr *) &v, sizeof(v));
n=sizeof(v);
printf("n=%d\n",n);
int cnt =0;
connect (sfd, (struct sockaddr *)&v , n);
perror("connect");
while(1)
{
if(cnt == 0) //if condition transfer user name on client side.
{
write (sfd,client,strlen(client)+1);
bzero(b,sizeof(b));
cnt++;
sleep(1);
recv(sfd,b,sizeof(b),0);
strcpy(server,b);
}
else // else condition use for normal cheting.
{
printf("%s>>",client);
fgets(a,sizeof(a),stdin);
if(a[0]=='q')
{
close(sfd);
break;
}
write (sfd,a,sizeof(a));
sleep(1);
bzero(b,sizeof(b));
read(sfd,b,sizeof(b));
printf("%s:%s",server,b);
}
}
}
No comments:
Post a Comment