printf网络数据

时间:2012-08-05 17:09:28

标签: c++ linux sockets udp

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

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显示000010001它意味着5个字节,我需要检查它并与我的数据进行比较。

1 个答案:

答案 0 :(得分:3)

unsigned int maximumPacketSize = sizeof(buffer);//frameSize ;

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

本质上意味着,你永远不会超过4个字节。