1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <sys/ioctl.h>
5 #include <sys/socket.h>
6 #include <arpa/inet.h>
7 #include <unistd.h>
8 
9 #include <net/if.h>
10 #include <netinet/in.h>
11 
12 // This code compiles on FreeBSD and Linux but did not work on FreeBSD
13 
14 /* Promisc management on FreeBSD is real nighmare, really. Issues with: ifr_flagshigh and IFF_PPROMISC vs IFF_PROMISC */
15 /* Good code examples here: https://github.com/fichtner/netmap/blob/master/extra/libpcap-netmap.diff */
16 
main()17 int main() {
18     // We need really any socket for ioctl
19 
20     int fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
21 
22     if (!fd) {
23         printf("Can't create socket\n");
24         exit(1);
25     }
26 
27     struct ifreq ethreq;
28     memset(&ethreq, 0, sizeof(ethreq));
29     strncpy(ethreq.ifr_name, "eth6", IFNAMSIZ);
30 
31     int ioctl_res = ioctl(fd, SIOCGIFFLAGS, &ethreq);
32 
33     if (ioctl_res == -1) {
34         printf("Can't get interface flags");
35         exit(1);
36     }
37 
38     if (ethreq.ifr_flags & IFF_PROMISC) {
39         printf("Interface in promisc mode already\n");
40 
41         printf("Switch it off\n");
42 
43         ethreq.ifr_flags &= ~IFF_PROMISC;
44 
45         int ioctl_res_set = ioctl(fd, SIOCSIFFLAGS, &ethreq);
46 
47         if (ioctl_res_set == -1) {
48             printf("Can't set interface flags");
49             exit(1);
50         }
51 
52         printf("promisc mode disabled correctly\n");
53     } else {
54         printf("Interface in non promisc mode now, switch it on\n");
55 
56         ethreq.ifr_flags |= IFF_PROMISC;
57         int ioctl_res_set = ioctl(fd, SIOCSIFFLAGS, &ethreq);
58 
59         if (ioctl_res_set == -1) {
60             printf("Can't set interface flags");
61             exit(1);
62         }
63 
64         printf("promisc mode enabled\n");
65     }
66 
67     close(fd);
68 }
69