C: Linux 到 Windows:通过 TCP 发送文本文件在 Windows 端产生不精确的副本

标签 c linux windows sockets tcp

我正在编写一个系统来收集 Mac 上的软件/硬件信息,并将其放入基于 Windows 的 SQLite3 数据库中。

架构如下:

  • Mac 上的代理 - 收集数据,然后使用 SSL 通过 Internet 将其发送到 DMZ 中的小型 Linux 服务器(到目前为止,这部分工作正常)
  • Linux 服务器连接到内部 Windows 服务器并发送相同的数据

在第二点出现了问题。 Linux 服务器连接到 Windows 一台,好的,Windows 收到数据,并以正确的名称保存它,但数据本身有些拙劣。

这是一个例子。 这是条目在 OS X/Linux 中的样子:

Microsoft Word — Windows 8
VMware Fusion 7.1.1

条目在 Windows 上的外观:

Microsoft Word — Windows 8
VMware Fusion 7.1.1

(VMWare Fusion 7.1.1是版本) 长破折号替换为三个符号。我怀疑编码。

这是我发送文件的代码:

    do {

    fgets(buf, BLEN, file_d);
    ch = feof(file_d);
    if(ch == 0){
        if((send(sockfd, buf, strlen(buf), 0)) < 0){
            fprintf(stderr, "[%d][%s]: Error sending data.\n", getpid(), APPNAME);
            return 10;
        };
    }
    else break;

    memset(&buf, 0, sizeof(buf));

}while(!feof(file_d));

(其中 BLEN = 1024)

现在,我知道这不是读取文件的最佳方式(实际上我认为它应该是 while(fgets(buf, BLEN, file_d) != NULL)),但它适用于我(我很可能会将其重写为 kosher),我认为这不是这里的问题。

这是 Windows 部分:

while (1) {
    memset(&buf, 0, sizeof(buf));
    if ((bytes_read = recv(newsock, buf, sizeof(buf), 0)) > 0){
        fprintf(comp_fd, "%s", buf);
        printf("%s", buf);
        continue;
    }
    else if ((bytes_read = recv(newsock, buf, sizeof(buf), 0)) == 0){
        mytime = time(NULL);
        memset(&t, 0, 25);
        strncat(t, ctime(&mytime), 24);
        fprintf(log_fd, "[%lu][SERVER]: Connection with %S closed at %s.\n", GetCurrentThreadId(), temp_wstruct->s, t);
        close(newsock);
        break;
    }
    else
    {
        fprintf(log_fd, "[%lu][SERVER]: Error while receiving.", GetCurrentThreadId());
        close(newsock);
        fclose(log_fd);
        fclose(comp_fd);
        ExitThread(-1);
        break;
    }
}

正如我所说,文件确实已收到并保存,除了这些奇怪的符号。 谁能给点建议?

最佳答案

  1. 发送时,您假设数据以 null 结尾:

        if((send(sockfd, buf, strlen(buf), 0)) < 0){
    

    您应该使用 read 方法实际返回的计数,而不应该为此目的使用 fgets()

  2. 您的接收循环毫无意义。您多次调用 recv() 并且每次都在不同的条件下测试结果,当您得到非失败结果时,您没有做正确的事情。它应该是这样的:

    while ((bytesRead = recv(newsock, buf, sizeof buf, 0)) > 0)
    {
        write(filefd, buf, bytesRead);
    }
    if (bytesRead == -1)
    {
        perror("recv()");
    }
    // else it was zero which is end of stream, no error.
    

关于C: Linux 到 Windows:通过 TCP 发送文本文件在 Windows 端产生不精确的副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30913318/

相关文章:

c - C 中整数的顺序颠倒

ruby-on-rails - 在生产中使用 Sunspot 时设置独立 solr 服务器的原因?

linux - 设置ACL权限后用户无法访问文件夹

windows - 在 Windows 10 上将选美与 VSCode 结合使用

c - 将 C 代码从一个操作系统移植到另一个操作系统时处理静态库

c - 如何从源代码生成 .cpp 文件?

linux - linux中真的没有超过6个参数的系统调用吗?

c - Visual-C Win32 API 分层窗口闪烁

windows - USN NFTS 变化通知事件中断

c - 如何将 int 转换为 char 字符串