^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 1) /* SPDX-License-Identifier: GPL-2.0 */
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 2) #include <stdlib.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 3) #include <stdio.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 4) #include <linux/unistd.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 5) #include <unistd.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 6) #include <string.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 7) #include <errno.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 8) #include <linux/if_ether.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 9) #include <net/if.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 10) #include <linux/if_packet.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 11) #include <arpa/inet.h>
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 12)
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 13) static inline int open_raw_sock(const char *name)
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 14) {
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 15) struct sockaddr_ll sll;
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 16) int sock;
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 17)
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 18) sock = socket(PF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL));
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 19) if (sock < 0) {
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 20) printf("cannot create raw socket\n");
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 21) return -1;
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 22) }
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 23)
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 24) memset(&sll, 0, sizeof(sll));
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 25) sll.sll_family = AF_PACKET;
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 26) sll.sll_ifindex = if_nametoindex(name);
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 27) sll.sll_protocol = htons(ETH_P_ALL);
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 28) if (bind(sock, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 29) printf("bind to %s: %s\n", name, strerror(errno));
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 30) close(sock);
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 31) return -1;
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 32) }
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 33)
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 34) return sock;
^8f3ce5b39 (kx 2023-10-28 12:00:06 +0300 35) }