So I try to make a very simple mail server client on unix. Right now I create a socket at the server for listening and a socket at the client for sending messages to the server.
What I do at this point is create a connection and send a user name from the client to the server where the server will check it through a list and if it's valid will reply with ACCEPT.
Code:
server
...
loc_socket=socket(AF_UNIX,SOCK_STREAM,0);
unlink(SOCKFILE);
bzero(&addr,sizeof(addr));
addr.sa_family=AF_UNIX;
strcpy(addr.sa_data,SOCKFILE);
if (bind(loc_socket,&addr,sizeof(addr))<0) {
printf("Server bind failure %d\n",errno);
perror("Server:");
exit(1);
}
if (listen(loc_socket,LISTEN_Q)<0) {
printf("Server listen failure %d\n",errno);
perror("Server:");
exit(1);
}
for (;;) {
if ((rem_socket=accept(loc_socket,&client_addr,&client_len))<0){
printf("server accept failure%d\n",errno);
perror("Server: ");
}
assertUserName(&rem_socket,user_list);
close(rem_socket);
}
...
Code:
int assertUserName(int* socket,user* users){
int i, flag=0;
char buf[BUFFER_SIZE];
read(*socket,buf,sizeof(buf));
printf("%s\n",buf);
for (i=0; i<3; i++) {
if (strcmp(users[i].loginname,buf)==0) {
flag=1;
break;
}
printf("try %d --- flag %d\n",i,flag);
}
if (flag==1)
write(*socket,"ACCEPT\0",sizeof("ACCEPT\0"));
else
write(*socket,"REJECT\0",sizeof("REJECT\0"));
return 0;
}
Code:
client
...
loc_socket= socket(AF_UNIX,SOCK_STREAM,0);
addr.sa_family=AF_UNIX;
strcpy(addr.sa_data,SOCKFILE);
if (connect(loc_socket,&addr,sizeof(addr))<0) {
printf("Client connect failure %d\n",errno);
perror("Client:");
exit(1);
}
if (signIn(&loc_socket))
return 0;
...
Code:
int signIn(int* socket){
char user_name[LOGIN_NL];
char buf[BUFFER_SIZE];
printf("Log in: ");
fgets(user_name,sizeof(user_name),stdin);
printf("%s",user_name);
write(*socket,user_name,sizeof(user_name);
read(*socket,buf,sizeof(buf));
printf("server read '%s'\n",buf);
if(strcmp(buf,"REJECT")==0){
printf("User Name doesn't exist\n");
return 1;
}
return 0;
}
My problem is in the signIn function wher I get the user name with fgets.Right afterwards I print what is on the user_name variable and no matter what i write it prints back 0Υy9 or something and so does the server. I think the sending and receiving of the message works fine since the server prints out the same (I also tried and sent a string directly and it got through fine) so why does it store rubbish on the variable. At first I thought it had to do something with the buffer but i think thats silly since it's a short program and it closes afterwards so if someone had any idea I 'd appreciate it.
By the way I dont know if it has any relevance but I am writing it on unix and test it using two terminals on the same pc and same account...