1
1
// SPDX-License-Identifier: GPL-2.0 OR BSD-3-Clause
2
2
/* Copyright (c) 2022 Jacky Yin */
3
+ #include <argp.h>
3
4
#include <arpa/inet.h>
4
5
#include <assert.h>
5
6
#include <bpf/libbpf.h>
15
16
#include "sockfilter.h"
16
17
#include "sockfilter.skel.h"
17
18
19
+ static struct env {
20
+ const char * interface ;
21
+ } env ;
22
+
23
+ const char argp_program_doc [] =
24
+ "BPF socket filter demo application.\n"
25
+ "\n"
26
+ "This program watch network packet of specified interface and print out src/dst\n"
27
+ "information.\n"
28
+ "\n"
29
+ "Currently only IPv4 is supported.\n"
30
+ "\n"
31
+ "USAGE: ./sockfilter [-i <interface>]\n" ;
32
+
33
+ static const struct argp_option opts [] = {
34
+ { "interface" , 'i' , "INTERFACE" , 0 , "Network interface to attach" },
35
+ {},
36
+ };
37
+
38
+ static error_t parse_arg (int key , char * arg , struct argp_state * state )
39
+ {
40
+ switch (key ) {
41
+ case 'i' :
42
+ env .interface = arg ;
43
+ break ;
44
+ case ARGP_KEY_ARG :
45
+ argp_usage (state );
46
+ break ;
47
+ default :
48
+ return ARGP_ERR_UNKNOWN ;
49
+ }
50
+ return 0 ;
51
+ }
52
+
53
+ static const struct argp argp = {
54
+ .options = opts ,
55
+ .parser = parse_arg ,
56
+ .doc = argp_program_doc ,
57
+ };
58
+
18
59
static const char * ipproto_mapping [IPPROTO_MAX ] = {
19
60
[IPPROTO_IP ] = "IP" , [IPPROTO_ICMP ] = "ICMP" , [IPPROTO_IGMP ] = "IGMP" ,
20
61
[IPPROTO_IPIP ] = "IPIP" , [IPPROTO_TCP ] = "TCP" , [IPPROTO_EGP ] = "EGP" ,
@@ -99,6 +140,12 @@ int main(int argc, char **argv)
99
140
struct sockfilter_bpf * skel ;
100
141
int err , prog_fd , sock ;
101
142
143
+ env .interface = "lo" ;
144
+ /* Parse command line arguments */
145
+ err = argp_parse (& argp , argc , argv , 0 , NULL , NULL );
146
+ if (err )
147
+ return - err ;
148
+
102
149
/* Set up libbpf errors and debug info callback */
103
150
libbpf_set_print (libbpf_print_fn );
104
151
@@ -122,7 +169,7 @@ int main(int argc, char **argv)
122
169
}
123
170
124
171
/* Create raw socket for localhost interface */
125
- sock = open_raw_sock ("lo" );
172
+ sock = open_raw_sock (env . interface );
126
173
if (sock < 0 ) {
127
174
err = -2 ;
128
175
fprintf (stderr , "Failed to open raw socket\n" );
0 commit comments