【问题标题】:Appending data to a null character in character array to send data through socket将数据附加到字符数组中的空字符以通过套接字发送数据
【发布时间】:2009-09-15 02:01:12
【问题描述】:

我是一个新手程序员。我有一个问题如下,

void SockSend()  
{  
char *sendbuf;  
int sendsize;   /* send data size(variable size)*/  
int iPos = 0, iTotSize;  
char hdr;  
char *data = "ABCDEFGHIJKLMNO";   /* its just example, data can be any thing */  
sendsize = strlen(data);  

hdr = '\0';   /* header character */  
sendbuf = (char*)malloc(sendsize + 2);  
sendbuf[iPos] = hdr;  
iPos++;  
strncpy(sendbuf + iPos, data, 15);  
iPos += sendsize;  
sendbuf[iPos] = '\0';   /* append null at end of string*/  

iTotSize = strlen(sendbuf);  

send(sockid, sendbuf, iTotSize, 0);  
}

在上面的代码中,我需要发送带有标题字符的数据。 如果标题 ascii 字符介于 1h - ffh 之间,而不是 0h 可以正常工作。 我知道如果将 null 添加到字符串中,则将其视为字符串的结尾。 但我需要通过套接字发送带有数据的 NULL 字符。 谁能帮我解决这个问题。

提前谢谢你

【问题讨论】:

    标签: c sockets


    【解决方案1】:

    如果您想避免 Null 终止,则必须停止将数据视为字符串。 strcpy 旨在仅复制以空字符结尾的字符串。它被实现为复制每个字节,直到遇到#0。 memcpy 可以复制任何内存位置。它不受以空字符结尾的字符串的约束。由于 memcpy 无法确定要复制的数据的大小,因此您必须提供该信息。此外,您不应使用 strlen,因为它受相同的终止规则约束。

    【讨论】:

      【解决方案2】:
      iTotSize = strlen(sendbuf);
      

      strlen(sendbuf) 将在找到空字符后立即停止计算字符。

      通过手动添加各种尺寸来计算总尺寸。

      也许这会有所帮助:iTotSize = 1 + strlen(sendbuf + 1);

      【讨论】:

      • 嗨,尼克,非常感谢你的回复.. 你真是个天才
      • @mark4o,当然 ;-)(即使是 iTotSize = sendsize + 1,也可以)
      【解决方案3】:

      如果您必须处理包含'\0' 的数据,请将它们的大小分开并使用memcpy 而不是strcpystrncpy

      请注意,在您的示例中,您在将内存分配给sendbuf 时已经计算了数据包的正确长度。只需使用该值(-1)。另外,请注意您确保发送 buf 中有足够的数据空间,因此您可以安全地使用strcpystrncpy 在达到限制时不会终止输出字符串 - 容易出错。

      在 C 中使用 size 时,请使用在 stdlib.h 中定义的 size_t 类型,而不是 int

      希望对您有所帮助...

      void SockSend()  
      {  
          char *sendbuf;  
          int sendsize;   /* send data size(variable size)*/  
          int iPos = 0, iTotSize;  
          char hdr;  
          char *data = "ABCDEFGHIJKLMNO"; 
          sendsize = strlen(data);  /* -- Are you sure that data will not contain \0 ? */
      
          hdr = '\0';   /* header character */
          sendbuf = (char*)malloc(sendsize + 2);  /* -- Data size calculation! */
          sendbuf[iPos] = hdr;  
          iPos++;  
          strcpy(sendbuf + iPos, data);  
          iPos += sendsize;  
          sendbuf[iPos] = '\0';   /* append null at end of string*/  
      
          iTotSize = strlen(sendbuf);  
      
          send(sockid, sendbuf, iTotSize, 0);  
      }
      

      【讨论】:

        【解决方案4】:

        strlen 在 NUL 字符处停止,不计算它。 您可以简单地在该长度上添加一个

        【讨论】:

          【解决方案5】:

          因为还没有人指出这一点 - 你有一个 内存泄漏 这里。 您需要在发送字节后和从函数返回之前在某处调用free(sendbuf);

          sent() 也有可能返回 短计数 - 当 TCP 堆栈接受的数据少于您提供的数据时,即套接字发送缓冲区已满 - 因此您必须检查返回值。

          【讨论】:

            猜你喜欢
            • 2011-03-30
            • 1970-01-01
            • 2012-06-09
            • 1970-01-01
            • 2016-04-06
            • 1970-01-01
            • 2011-06-09
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多