Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
//#include "unp.h"
void readwrite(int, int, int); /* function prototype */
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen, pid;
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
while (1) {
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork();
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(sockfd);
int x,y,x1,y1,i=0,n,choice;
char buffer[256],ex[256];
FILE *fp;
printf("Incoming connection from %s - sending welcome\n", inet_ntoa(cli_addr));
n = write(newsockfd," welcome \n - select one \n r for registration \n l for login",145);
if (n < 0) error("ERROR writin to socket");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
if(*buffer == 'r')
{
// n = write(newsockfd," welcome \n - please Enter a user name:",45);
// if (n < 0) error("ERROR writing to socket");
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
fp=fopen(buffer,"a+");
fwrite(buffer,1,strlen(buffer),fp);
n = write(newsockfd,"\n your user name is your password:",45);
if (n < 0) error("ERROR writing to socket");
fclose(fp);
exit(0);
}
if(*buffer == 'l')
{
char key[256];
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
fp=fopen(buffer,"r");
if(fp=='\0')
{
n = write(newsockfd,"\n No user exist:",45);
if (n < 0) error("ERROR writing to socket");
// n = write(newsockfd,"\n please register :",45);
// if (n < 0) error("ERROR writing to socket");
}
else
{
bzero(buffer,256);
n = read(newsockfd,buffer,255);
fscanf(fp,"%s",key);
if(strcmp(buffer,key)!=0)
{
n = write(newsockfd,"\nunsucessful login:",45);
// if (n < 0) error("ERROR writing to socket");
break;
}
n = write(newsockfd,"\n loged:",45);
if (n < 0)
error("ERROR writing to socket");
}
}
srand((unsigned)time(3));
x=rand()%4;
y=rand()%4;
readwrite(newsockfd,x,y);
exit(0);
}
else close(newsockfd);
} /* end of while */
return 0; /* we never get here */
}
void readwrite(int sock,int x ,int y)
{
int n;
char buffer[256];
printf("x=%d y=%d",x,y);
while(1){
bzero(buffer,256);
n = read(sock,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Client: %s\n",buffer);
n = write(sock,"Server :msg reached",25);
if (n < 0) error("ERROR writing to socket");
}
}