c - 当通过 ip_mreqn 设置多播传出接口(interface)时,Sendto 返回 -1 和 errno 22(无效参数)

标签 c linux sockets unix network-programming

当我尝试通过下面的代码设置预期的传出接口(interface)来发送到多播组时,我遇到了一个问题,实际上当条件为真时 (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);

最佳答案

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

关于c - 当通过 ip_mreqn 设置多播传出接口(interface)时,Sendto 返回 -1 和 errno 22(无效参数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15789692/

相关文章:

c++ - 如何使 SIGSEGV 处理程序仅在堆栈溢出情况下在备用堆栈上启动?

linux - glibc 中这段代码段的目的是什么

linux - c++ ~ 共享对象 -> 获取主机应用程序偏移量

c - Winsock recv() 没有收到任何数据 (C)

sockets - bind() - 如何在同一个套接字上多次调用 bind()

c - C 中的 fread 和 fwrite

c - 在 C 中操作和跟踪循环的整数

c - C 中的格式说明符 - %s inside %s

python - 每天使用 twisted 重置 redis 键

linux - UDP 套接字和 MSG_PEEK