Using the server and client code. I tried adding ls functionality implemented via the readdir()
My *connection_handler looks like this:
void *connection_handler(void *socket_desc)
{
//Get the socket descriptor
int sock = *(int*)socket_desc;
int n;
int user_exists = 0;
char sendBuff[3000], client_message[2000];
char *command;
char home_dir[500] = "simple_slash/simple_home/";
char pwd[500];
DIR *direc;
struct dirent *temp_name;
while((n=recv(sock,client_message,2000,0))>0) {
//send(sock,client_message,n,0);
if (user_exists!=0) {
printf("inside if case\n");
/* get the first token */
command = strtok(client_message," ");
printf("%s\n",command );
if (strcmp(command,"ls")==0) {
printf("inside ls\n");
command = strtok(NULL, " ");
//ls ki permissions ka check
//strcat(pwd,command);
printf("%s\n", pwd);
if ((direc= opendir (pwd)) != NULL) {
/* print all the files and directories within directory */
strcpy(sendBuff,"\0");
while ((temp_name = readdir (direc)) != NULL) {
strcat(sendBuff,temp_name->d_name);
strcat(sendBuff,"\n");
// printf ("%s\n", temp_name->d_name);
}
send(sock, sendBuff,sizeof(sendBuff),0);
closedir (direc);
} else {
perror ("could not open directory ");
//return EXIT_FAILURE;
}
}
else if (strcmp(command,"fput")==0) {
printf("inside fput\n");
}
else if (strcmp(command,"fget")==0) {
}
else if (strcmp(command,"create_dir")==0) {
/* code */
}
else {
n=0;
send(sock, "Invalid command. Please try again.",n,0);
}
}
else {
user_exists = 1;
strcat(client_message,"\0");
strcat(pwd,home_dir);
strcat(pwd,client_message);
mkdir (pwd, 0777);
strcpy(sendBuff,"Welcome, ");
strcat(sendBuff,client_message);
strcat(sendBuff,"\n");
send(sock, sendBuff,sizeof(sendBuff),0);
}
memset(client_message, 0, 2000);
}
close(sock);
if(n==0)
{
puts("Client Disconnected");
}
else
{
perror("recv failed");
}
return 0;
}
When i run the ls command on the client side the code runs perfectly on the server side (verified by the printf statements in between)
But the output is returned on the client side every third time.
Server side terminal ouput:
abc@ubuntu:~/SE/hw1$ ./server
Socket created
bind done
Waiting for incoming connections...
Connection accepted
Handler assigned
inside if case
ls
inside ls
simple_slash/simple_home/user2
inside if case
ls
inside ls
simple_slash/simple_home/user2
inside if case
ls
inside ls
simple_slash/simple_home/user2
inside if case
ls
inside ls
simple_slash/simple_home/user2
inside if case
ls
inside ls
simple_slash/simple_home/user2
Client Side terminal output:
abc@ubuntu:~/SE/hw1$ ./client
Connected successfully.
Enter Username : user2
Welcome, user2
ls
ls
..
folder1
.
ls
ls
ls
..
folder1
.
Line 1: Welcome < username >
Line 2: ls
Line 3: ls Gives output
Line 1: ls
Line 2: ls
Line 3: ls Gives output
What am i doing wrong here ?