简体   繁体   English

当* from *传递时,recvfrom返回无效参数

[英]recvfrom returns invalid argument when *from* is passed

I am currently writing a small UDP server program in linux. 我目前正在linux中编写一个小型UDP服务器程序。 The UDP server will receive packets from two different peers and will perform different operations based on from which peer it received the packet. UDP服务器将接收来自两个不同对等体的分组,并将基于其从哪个对等体接收分组来执行不同的操作。 I am trying to determine the source from where I receive the packet. 我正在尝试确定收到数据包的来源。 However, when select returns and recvfrom is called, it returns with an error of Invalid Argument . 但是,当select返回并调用recvfrom ,它将返回错误的Invalid Argument If I pass NULL as the second last arguments, recvfrom succeeds. 如果我将NULL作为倒数第二个参数传递,则recvfrom成功。

I have tried declaring fromAddr as struct sockaddr_storage , struct sockaddr_in , struct sockaddr without any success. 我已经尝试将fromddr声明为struct sockaddr_storagestruct sockaddr_instruct sockaddr但没有任何成功。 Is their something wrong with this code? 这段代码有问题吗? Is this the correct way to determine the source of the packet? 这是确定数据包来源的正确方法吗?

The code snippet follows. 代码片段如下。

`           
    /*TODO : update for TCP. use recv */
    if((pkInfo->rcvLen=recvfrom(psInfo->sockFd,
                                pkInfo->buffer,
                                MAX_PKTSZ,
                                0,
                               /* (struct sockaddr*)&fromAddr,*/
                               NULL,
                              &(addrLen)
                              )) < 0)
    {
       perror("RecvFrom failed\n");
    }
    else
    {
       /*Apply Filter */
    #if 0
       struct sockaddr_in* tmpAddr;
       tmpAddr = (struct sockaddr_in* )&fromAddr;
       printf("Received Msg From %s\n",inet_ntoa(tmpAddr->sin_addr));
    #endif
      printf("Packet Received of len = %d\n",pkInfo->rcvLen);
    }

`

You must initialise addrLen to sizeof fromAddr before calling recvfrom() - it is an input/output parameter. 在调用recvfrom()之前,必须将addrLen初始化为sizeof fromAddr - 它是一个输入/输出参数。 Using struct sockaddr_storage to declare fromAddr is correct. 使用struct sockaddr_storage声明fromAddr是正确的。

I had the same problem: 我有同样的问题:

Invalid arguments 'Candidates are: int recvfrom(int, void *, unsigned int, int,
                   sockaddr *, unsigned int *) '

in same code: 在相同的代码中:

recvfrom(sockFd, buffer, MAX_PKTSZ, 0, (struct sockaddr*)&fromAddr, &addrLen)

My mistake was that i used ordinary int type instead of unsigned int for addrLen : 我的错误是我为addrLen使用了普通的int类型而不是unsigned int

unsigned int addrLen;
addrLen = sizeof(fromAddr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM