1 #include <bpf/libbpf.h>
2 #include <linux/if_link.h>
3 #include <net/if.h>
4 #include <string.h>
5
main(int argc,char ** argv)6 int main(int argc, char **argv) {
7 int i, ifindex;
8 __u32 curr_prog_fd=0;
9 int prog_fd;
10 for (i=1; i<argc; i++) {
11 ifindex = if_nametoindex(argv[i]);
12 if (!ifindex) {
13 perror("if_nametoindex");
14 return 1;
15 }
16 if (bpf_get_link_xdp_id(ifindex, &curr_prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST)) {
17 printf("bpf_get_link_xdp_id failed\n");
18 return 1;
19 }
20 if (curr_prog_fd) {
21 printf("xdp prog id(%d) already linked to %s, removing it now..\n", curr_prog_fd, argv[i]);
22 bpf_set_link_xdp_fd(ifindex, -1, XDP_FLAGS_UPDATE_IF_NOEXIST);
23 }
24 }
25 // load bpf object
26 struct bpf_prog_load_attr prog_load_attr = {
27 .prog_type = BPF_PROG_TYPE_XDP,
28 .file = "./ipfirewall_kern.o",
29 };
30 struct bpf_object *obj;
31 if (bpf_prog_load_xattr(&prog_load_attr, &obj, &prog_fd)) {
32 perror("Fail to load bpf object");
33 return 1;
34 }
35 for (i=1; i<argc; i++) {
36 ifindex = if_nametoindex(argv[i]);
37 if (bpf_set_link_xdp_fd(ifindex, prog_fd, XDP_FLAGS_UPDATE_IF_NOEXIST) < 0) {
38 printf("Fail to link to %s\n", argv[i]);
39 for (i--; i>=1; i--) {
40 bpf_set_link_xdp_fd(ifindex, -1, XDP_FLAGS_UPDATE_IF_NOEXIST);
41 }
42 return 1;
43 }
44 }
45 return 0;
46 }
47