Question

I am trying to open a raw socket to deal with traffic. I need it to be promiscuous. I have looked at lots of resources but I am totally confused. Here is my code:

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;
}

The final setsockopt() fails with error message "Protocol not available".
What could be the reason? Any suggestion?

Was it helpful?

Solution

It's because you use SOL_PACKET which is only used for packet(7) sockets. For raw INET sockets, you don't need that option.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top