我正在尝试打开一个原始套接字来处理udp流量。我需要它是混杂的。我看了很多资源,但我完全糊涂了。 这是我的代码:
char interface_name[12];
strcpy(interface_name, "eth1");
sd = socket(AF_INET, SOCK_RAW, IPPROTO_UDP);
if ( sd == -1 ) {
perror("error in opening socket.");
return;
}
if ( setsockopt(sd, SOL_SOCKET, SO_BINDTODEVICE, interface_name, strlen(interface_name)) == -1 )
{
perror("error in binding sd.");
return;
}
int one = 1;
if ( setsockopt (sd, IPPROTO_IP, IP_HDRINCL, &one, sizeof(one)) < 0)
{
perror("error in setting HDRINCL.");
return;
}
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, interface_name);
if (ioctl(sd, SIOCGIFINDEX, &ifr) < 0) {
perror("ioctl(SIOCGIFINDEX) failed");
return;
}
int interface_index = ifr.ifr_ifindex;
ifr.ifr_flags |= IFF_PROMISC;
if( ioctl(sd, SIOCSIFFLAGS, &ifr) != 0 )
{
perror("ioctl for IFF_PROMISC failed.");
return;
}
struct packet_mreq mr;
memset(&mr, 0, sizeof(mr));
mr.mr_ifindex = interface_index;
mr.mr_type = PACKET_MR_PROMISC;
if (setsockopt(sd, SOL_PACKET, PACKET_ADD_MEMBERSHIP, &mr, sizeof(mr)) < 0) {
perror("setsockopt(PACKET_MR_PROMISC) failed");
return 1;
}
最终的setsockopt失败,错误消息“Protocol not available”。可能是什么原因?有什么建议吗?