我正在尝试使用 setsockopt 函数将地址添加到接口的多播地址列表中,但是它使用errno EINVAL失败。我在内核代码中添加了一些printk,看起来errno最终是在内核 packet_setsockopt 函数中设置的,因为 optlen 传递的值小于 packet_mreq 结构的大小。对于我的生活,我无法弄清楚为什么会这样。以下是相关代码:
int addMulticastAddress(int ifindex, unsigned char macaddr[6]) {
struct packet_mreq mreq;
int fd;
int ret = -1;
if ((fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) < 0) {
return -1;
}
memset(&mreq, 0, sizeof(struct packet_mreq));
mreq.mr_ifindex = ifindex;
mreq.mr_type = PACKET_MR_MULTICAST;
memcpy(mreq.mr_address, macaddr, 6);
mreq.mr_alen = 6;
if (setsockopt(fd, SOL_PACKET,
PACKET_ADD_MEMBERSHIP,
&mreq, sizeof(struct packet_mreq) < 0)) {
virReportSystemError(errno,
_("Failed to %s %s %s multicast list for '%s' interface"),
add ? "add" : "delete",
virMacAddrFormat(macaddr, macstr),
add ? "to" : "from", ifname);
goto cleanup;
}
ret = 0;
cleanup:
close(fd);
return ret;
}
答案 0 :(得分:1)
你的一个括号是错误的地方:
if (setsockopt(fd, SOL_PACKET,
PACKET_ADD_MEMBERSHIP,
&mreq, sizeof(struct packet_mreq) < 0)) {
应该是:
if (setsockopt(fd, SOL_PACKET,
PACKET_ADD_MEMBERSHIP,
&mreq, sizeof(struct packet_mreq)) < 0) {