162306a36Sopenharmony_ci/* SPDX-License-Identifier: GPL-2.0 */
262306a36Sopenharmony_ci#include <stdlib.h>
362306a36Sopenharmony_ci#include <stdio.h>
462306a36Sopenharmony_ci#include <linux/unistd.h>
562306a36Sopenharmony_ci#include <unistd.h>
662306a36Sopenharmony_ci#include <string.h>
762306a36Sopenharmony_ci#include <errno.h>
862306a36Sopenharmony_ci#include <linux/if_ether.h>
962306a36Sopenharmony_ci#include <net/if.h>
1062306a36Sopenharmony_ci#include <linux/if_packet.h>
1162306a36Sopenharmony_ci#include <arpa/inet.h>
1262306a36Sopenharmony_ci
1362306a36Sopenharmony_cistatic inline int open_raw_sock(const char *name)
1462306a36Sopenharmony_ci{
1562306a36Sopenharmony_ci	struct sockaddr_ll sll;
1662306a36Sopenharmony_ci	int sock;
1762306a36Sopenharmony_ci
1862306a36Sopenharmony_ci	sock = socket(PF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL));
1962306a36Sopenharmony_ci	if (sock < 0) {
2062306a36Sopenharmony_ci		printf("cannot create raw socket\n");
2162306a36Sopenharmony_ci		return -1;
2262306a36Sopenharmony_ci	}
2362306a36Sopenharmony_ci
2462306a36Sopenharmony_ci	memset(&sll, 0, sizeof(sll));
2562306a36Sopenharmony_ci	sll.sll_family = AF_PACKET;
2662306a36Sopenharmony_ci	sll.sll_ifindex = if_nametoindex(name);
2762306a36Sopenharmony_ci	sll.sll_protocol = htons(ETH_P_ALL);
2862306a36Sopenharmony_ci	if (bind(sock, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
2962306a36Sopenharmony_ci		printf("bind to %s: %s\n", name, strerror(errno));
3062306a36Sopenharmony_ci		close(sock);
3162306a36Sopenharmony_ci		return -1;
3262306a36Sopenharmony_ci	}
3362306a36Sopenharmony_ci
3462306a36Sopenharmony_ci	return sock;
3562306a36Sopenharmony_ci}
36