我编写了简单的客户端-服务器应用程序,使用 TCP 套接字将文件从一台计算机复制到另一台计算机。
在同一台计算机上复制文件在验证文件的 md5sum 时成功,但在复制到远程计算机时失败:(
本地副本
$>my_copy file.tar.gz root@127.0.0.1:/home/viswesn/file.tar.gz
$>md5sum 文件.tar.gz
199b341684f528012e44dbf13512c5fc
$>md5sum/home/viswesn/file.tar.gz
199b341684f528012e44dbf13512c5fc
远程复制
$>my_copy file.tar.gz root@blrlapx12:/home/viswesn/file.tar.gz
$>md5sum 文件.tar.gz
199b341684f528012e44dbf13512c5fc
$>md5sim/home/viswesn/file.tar.gz
d4cbf92a9d2ed632e429c69334c6bf7a
服务器端代码
int sendFile(int sock, FILE *fp, long int size) {
int rc = -1;
char dir[DIRSIZE + 1] = {'\0'};
long int nsend = 0;
int nread = DIRSIZE;
int wc = -1;
nleft = size;
while (!feof(fp)) {
rc = fread(dir, sizeof(char), nread, fp);
nsend += rc;
if (rc > 0) {
printf("Sending %ld of %ld bytes\r", nsend, size);
wc = write(sock, dir, rc);
if (wc != rc) {
printf("failed to write to sock %d %s\n", sock, strerror(errno));
goto end;
}
}
bzero(dir, rc + 1);
}
printf("\n");
rc = 0;
end:
if (sock) {
close(sock);
}
return (rc);
}
客户端代码
int getFile(int sock, char *filename, long int startOffSet, long int size) {
char dir[DIRSIZE + 1] = {'\0'};
int rc = -1;
FILE *fp = NULL;
int cnt = 0;
int nread = DIRSIZE;
long int nrecv = 0;
int wc = 0;
long int nleft = size;
fp = fopen(filename, "w");
if (fp == NULL) {
printf("unable to open file %s %s\n", filename, strerror(errno));
} else {
printf("open file %s success\n", filename);
}
while(nleft > 0) {
if (nleft < nread) {
nread = nleft;
}
cnt = read(sock, dir, nread);
if (cnt <= 0) {
goto end;
}
nleft -= cnt;
nrecv += cnt;
dir[cnt] = '\0';
wc = write(fp, dir, cnt);
if (wc != cnt) {
printf("\nFailed to write to %d", fileno(fp));
break;
}
printf("Writing %d - [Recv : %ld] / [ Total : %ld] bytes\r", cnt, nrecv, size);
}
if (nrecv != size) {
printf("\nFailed to get file data %ld/%ld - diff of %ld\n", nrecv, size, size - nrecv);
goto end;
}
printf("\n");
rc = 0;
end:
if (fp != NULL) {
/* close descriptor for file that was sent */
printf("Closing file descriptor %d\n", fileno(fp));
fclose(fp);
}
return (rc);
}
最佳答案
对于客户端,您正在以文本模式打开文件。
fp = fopen(filename, "w");
如果客户端和服务器所在的操作系统使用不同的行尾,这可能会导致问题。例如 Unix 和 Windows。 尝试以二进制模式打开文件。
fp = fopen(filename, "wb");
如果这没有帮助,请使用 kdiff3 等比较文件并检查差异在哪里。
关于c - md5sum 从套接字接收文件时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11765748/