Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

c++ - UDP packages aren't recieved compleatly, recvfrom returns always 1

I'm trying to process some UDP packages. Opening sockets and so on works well, I do get packages and I get the source IP and port.The port is set in m_port and the IP in m_ipfilter. However recvfrom always returns 1. My code is basically the example code and according to wireshark there are packages with a length of 998 incoming. Does somebody know what I'm doing wrong? The buffer is at the moment 2k long.

   struct sockaddr_in server, from;
    int sock, flen = sizeof(from);
    char buf[BUFLEN];

    if ((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
    {
        std::cerr << "Couldn't open socket: " << strerror(errno) << ", errno: " << errno << std::endl;
        return;
    }
    memset((char *)&server, 0, sizeof(server)); //zero the structure
    server.sin_family = AF_INET;
    server.sin_port = htons(m_port);
    server.sin_addr.s_addr = htonl(m_ipfilter); //zero is recive on any adrress, INADDR_ANY=0
    if (bind(sock, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
        std::cerr << "Couldn't bind socket on port: " << m_port << " : " << strerror(errno) << ", errno: " << errno << std::endl;
        return;
    }
    while (1)
    {
        ssize_t recv_len = 0;
        if (recv_len = recvfrom(sock, buf, sizeof(buf), 0, (struct sockaddr *)&from, (socklen_t *)&flen) != -1) //there is data
        {
            processOutput(buf, recv_len, from, (socklen_t)flen);
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The condition recv_len = recvfrom(...) != -1 is treated as recv_len = (recvfrom(...) != -1).

This will assign recv_len to the comparision result, so it will become 1 if the return value of recvfrom is not -1 and become 0 if the return value is -1.

The condition should be (recv_len = recvfrom(...)) != -1. Add parenthesis to compare the return value of recvfrom with -1 without assigning the comparision result to recv_len.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...