当我尝试通过下面的代码设置预期的传出接口(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/