0001
0002 #include <stdlib.h>
0003 #include <stdio.h>
0004 #include <linux/unistd.h>
0005 #include <unistd.h>
0006 #include <string.h>
0007 #include <errno.h>
0008 #include <linux/if_ether.h>
0009 #include <net/if.h>
0010 #include <linux/if_packet.h>
0011 #include <arpa/inet.h>
0012
0013 static inline int open_raw_sock(const char *name)
0014 {
0015 struct sockaddr_ll sll;
0016 int sock;
0017
0018 sock = socket(PF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL));
0019 if (sock < 0) {
0020 printf("cannot create raw socket\n");
0021 return -1;
0022 }
0023
0024 memset(&sll, 0, sizeof(sll));
0025 sll.sll_family = AF_PACKET;
0026 sll.sll_ifindex = if_nametoindex(name);
0027 sll.sll_protocol = htons(ETH_P_ALL);
0028 if (bind(sock, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
0029 printf("bind to %s: %s\n", name, strerror(errno));
0030 close(sock);
0031 return -1;
0032 }
0033
0034 return sock;
0035 }