【问题标题】:printf network dataprintf 网络数据
【发布时间】:2012-08-05 17:09:27
【问题描述】:

我写了以下函数并且工作正常:

int NetworkSocket::readDatagrams(unsigned char *buffer, string &srcAddress, unsigned short int & srcPort,size_t frameSize)
{

    unsigned int maximumPacketSize = sizeof(buffer);//frameSize ;
    int returnValue ;
    sockaddr_in from;
    socklen_t fromLength = sizeof( from );
    int receivedBytes;

    fromLength = sizeof(this->getSocketAddressStructureOfServer());
    receivedBytes = recvfrom( this->socketFD, buffer, maximumPacketSize, 0, (sockaddr *)&this->getSocketAddressStructureOfServer(), &fromLength     ) ;

    cout << receivedBytes << endl;
    returnValue = receivedBytes;
    if ( receivedBytes <= 0 )
        returnValue = -1;

    /// exporting data
    //
    srcAddress = inet_ntoa(this->getSocketAddressStructureOfServer().sin_addr);
    srcPort = ntohs( ( unsigned short int)this->getSocketAddressStructureOfServer().sin_port );


    return returnValue;
}

当我应用它时,它在 ref srcAddress 和端口中返回,即使缓冲区已满,但我无法 printf 缓冲区,我该怎么做? wireshakr show 000010001 这意味着 5 个字节,我需要检查它并与我的数据进行比较。

【问题讨论】:

  • 请注意,unsigned int maximumPacketSize = sizeof(buffer); 将最大数据包大小设置为 char* 的大小,通常为 4 或 8 个字节。
  • 另外,我看不到 printf 失败的确切行...或任何 printf,就此而言。
  • :: 是 C 中的语法错误。可能是 C++ 吗?

标签: c++ linux sockets udp


【解决方案1】:
unsigned int maximumPacketSize = sizeof(buffer);//frameSize ;

这一行有问题,因为您请求的是指针变量的大小(在 32 位系统上总是等于 '4')。您必须手动传递最大缓冲区大小,或者只是“知道”它,这应该不是问题,因为您首先实例化了它。

从本质上讲,你永远不能得到超过 4 个字节。

【讨论】:

  • 现在,您对检查它们有什么想法吗?
  • 检查到底是什么?缓冲区的内容?你是在传送号码吗?一个字符串?如果是数字,请尝试使用 printf("%d", *((int *)buffer));,它将临时将缓冲区转换为 'int * Array' 并返回第一个元素。如果要传输字符串,请使用 printf("%s", Buffer);,但请确保字符串以 '0' 结尾。
猜你喜欢
  • 2019-07-05
  • 2011-11-02
  • 2010-12-10
  • 2020-09-18
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
相关资源
最近更新 更多