【问题标题】:Sendto returns -1 and errno 22 (Invalid argument), when set the multicast outgoing interface by ip_mreqn当通过 ip_mreqn 设置多播传出接口时,Sendto 返回 -1 和 errno 22(无效参数)
【发布时间】:2013-03-25 06:10:37
【问题描述】:

我遇到了一个问题,当我尝试通过以下代码设置预期的传出接口来发送到多播组时,实际上当条件为 TRUE (if(config.enable_if == 1)) sendto 系统调用返回错误 Invalid Argument,但如果条件是 False sendto 发送数据并且不会产生任何错误。

请任何人有想法,或者我应该修改我的代码中的任何内容吗?

    /* Create a datagram socket on which to send. */
    sd = socket(AF_INET, SOCK_DGRAM, 0);

    /* Set local interface for outbound multicast datagrams. */
    /* The IP address specified must be associated with a local */
    /* multicast capable interface. */
    if(config.enable_if == 1){
       mreqn.imr_ifindex = if_nametoindex("eth3");
       rc = setsockopt(sd, IPPROTO_IP, IP_MULTICAST_IF, (void *)&mreqn, sizeof(mreqn));
     }

    /* Initialize the group sockaddr structure with a */
    /* group address of dynamic address and port dynamic port. */
    memset((char *) &groupSock, 0, sizeof(groupSock));
    groupSock.sin_family = AF_INET;
    groupSock.sin_addr.s_addr = inet_addr(config.mip);
    groupSock.sin_port = htons(config.port);


    /* Send a message to the multicast group specified by the*/
    /* groupSock sockaddr structure. */

    rc = sendto(sd, (const char *)& databuf, datalen, 0, (const struct sockaddr*)&groupSock, sizeof (struct sockaddr));
    printf("errno %d\n",errno);

【问题讨论】:

  • 什么是databuf,它是如何声明的?与datalen相同?
  • 另外,请不要检查errno,除非您知道之前的呼叫失败。您必须始终先检查返回码。而且您也不会从 setsockopt 调用中检查失败。
  • 您应该检查 setsockopt() 是否失败,如果失败,它可能会提供进一步的线索。而且你不能在 sendto() 之后检查 errno,除非 sendto() 失败。如果 sendto 没有失败,谁知道 errno 是什么。
  • 是的,但我没有在此处添加它们。 rc 为 =-1 , char *databuf = malloc(1024) .... 不过这些东西不用管,只关注场景
  • 我也会检查 sesockopt 不用担心

标签: c linux sockets unix network-programming


【解决方案1】:

sendto 失败的一个原因是因为您向它传递了一个它不期望的数据指针。如果你有char* databuf 然后你做&databuf 你得到指针的地址,即指向指针的指针,类型为char**。如果您删除演员表(不需要),那么在编译时您至少会收到一个警告,甚至可能是一个错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-10
    • 2019-10-13
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多