0

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

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

4

1 回答 1

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

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

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

于 2012-08-05T17:13:05.223 回答