[u][u]Plaease help me to find my error, I have been trying for a while, cannot figure it out.
The file name from client to the server side over tcp is coming with some trash. Plaese see below.
[u]on client side:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* The buffer to store the file name*/
char fileNameBuff[100];
fileNameBuff[0]= '\0';
strncat (fileNameBuff, argv[3], 99);
printf ("filename: %s\n", fileNameBuff);
/*Sent file name size and file name to server */
int buffLen = strlen(fileNameBuff);
write(connfd, &buffLen, sizeof(int));
printf ("file size sent to server: %d\n", buffLen);
write(connfd, &fileNameBuff, buffLen);
printf ("filename sent to server: %s\n", fileNameBuff);
on the server side:
1 2 3 4 5 6 7 8 9 10
int fileNameLen = 0;
fprintf(stderr, "The fileName value - not really empty, shows some weird square with 0001: %s\n", fileNameBuff);
read(connfd, &fileNameLen, sizeof(int));
fprintf(stderr, "The file Name Len value received by server- shows correct value: %d\n", fileNameLen);
read(connfd, &fileNameBuff, fileNameLen);
fprintf(stderr, "The fileName recieved by the to server - getting name+bunch of TRASH: %s\n", fileNameBuff);
from server terminal:
Waiting for somebody to connect on port 1234
Connected!
The fileName value - empty:
The file Name Len value received by server: 8
The fileName received by the to server - name+trash: file.txtn>i����o}��z}�����������{�����p�x���tz}�
[/u][/u][/u]
You haven't supplied the code for the read(...) function, but it looks as if when it copies the filename into the fileNameBuff array that it isn't adding a Null terminator, and you are then seeing the content of the rest of the array containing random data.
When you declare the client side char array you would be better to use the strcpy or strcpy_s instead of stncat as strncat is for appending characters to the end of the existing string. You just want to copy the content of arg[3] to your char array.
On the client side, the code attempts to recognise that strncpy doesn't terminate the string if it fills the buffer, unfortunately you don't quite get it right.
1 2 3 4 5
/* The buffer to store the file name*/
char fileNameBuff[100];
fileNameBuff[99]= '\0'; /* you need a null in the last bytes */
strncat (fileNameBuff, argv[3], 99);
printf ("filename: %s\n", fileNameBuff);
As @ajh32 said, the server receives the data, but you don't null terminate the string. So the server side shoudl be something like:
1 2 3 4 5 6 7 8
char fileNameBuff[100]; /* 100 is largest len we receive, or we could do malloc(fileNameLen + 1) */
int fileNameLen = 0;
/* do the receive, remember to check return codes for errors */
memset(fileNameBuff, 0, sizeof(fileNameBuff));
read(connfd, &fileNameLen, sizeof(int));
read(connfd, fileNameBuff, fileNameLen);
fprintf(stderr, "The fileName recieved by the to server: %s\n", fileNameBuff);