Essentially I have am simulating a TCP connection with sockets and I am sending information between client and server between sockets. I want to use a single buffer for each file, but unfortunately when writing, it overwrites the buffer getting a bad/dirty string in line (B) with buffer containing something like noexistshed, the hed part, obviously being a remnant of Established from a previous message written.
At first the client prints Connection Status: Established just fine, but later on, because of this dirty buffer, the printf in line (C), prints 1, since "noexistshed" and "noexist" are different.
All buffers are declared as char buffer[1024];. Similarly user and pass are defined as char user[80] and char pass[80], (although I am seeking to make these 2 a single buffer).
This is the problematic section of the client:
read(clientSocket, buffer, 1024);
/*---- Print the received message ----*/
printf("Connection Status: %s\n", buffer);
printf("Please enter a username:\n");
scanf ("%s", user);
write(clientSocket, user, strlen(user)+1);
read(clientSocket, buffer, 80); // error happens here -- (B)
printf("%s comparison result %d", buffer, strcmp(buffer, "noexists")); // --- (C)
if(strcmp(buffer, "noexists") == 0)
{
printf("User doesn't exist\n");
exit(1);
}
This is the problematic section of the server:
strcpy(buffer,"Established.");
write(senderSocket,buffer,13,0);
memset(buffer,0,sizeof(buffer)); // ---- (A)
read(senderSocket, buffer, 80, 0);
int x;
for(x=0; x < 7 && strcmp(ul[0][0], buffer) != 0; x++);
printf("%d", x);
if(x == 7)
{
strcpy(buffer,"noexists");
} else {
strcpy(buffer,"exists");
}
write(senderSocket, buffer, strlen(buffer), 0);
read(senderSocket, buffer, 80, 0);
line (A) is what I presume might be the solution to my problems from what I have read in other questions/sites, but it is not working. I have also tried replacing it with buffer[0] = '\0'; and buffer[n] = '\0'; (with n being assigned the value of the read/write) with no luck. Also I've tried putting it after/before writes and reads, but there are just so many permutations that can be done, that I don't think I can solve it on my own. I would appreciate your help.