@@ -6,26 +6,21 @@ import (
66 "encoding/binary"
77 "fmt"
88 "log"
9- "net/netip"
109 "os"
1110 "os/signal"
1211 "syscall"
1312 "time"
1413 "unsafe"
1514
1615 bpf "github.com/aquasecurity/libbpfgo"
16+ "github.com/mozillazg/libbpfgo-tools/common"
1717 flag "github.com/spf13/pflag"
1818)
1919
20- const (
21- IPProtoTCP uint16 = 6
22- IPProtoUDP uint16 = 17
23- )
24-
25- type uint128 [16 ]byte
20+ const TASK_COMM_LEN = 16
2621
2722type BindEvent struct {
28- Addr uint128
23+ Addr common. Uint128
2924 TsUs uint64
3025 Pid uint32
3126 BoundDevIf uint32
@@ -34,11 +29,7 @@ type BindEvent struct {
3429 Proto uint16
3530 Opts uint8
3631 Ver uint8
37- Task [16 ]byte
38- }
39-
40- func (e BindEvent ) TaskString () string {
41- return string (bytes .TrimRight (e .Task [:], "\x00 " ))
32+ Task [TASK_COMM_LEN ]byte
4233}
4334
4435type Options struct {
@@ -86,22 +77,10 @@ func initGlobalVariable(bpfModule *bpf.Module, name string, value interface{}) {
8677 }
8778}
8879
89- func getCgroupDirFD (cgroupV2DirPath string ) (int , error ) {
90- const (
91- O_DIRECTORY int = 0200000
92- O_RDONLY int = 00
93- )
94- fd , err := syscall .Open (cgroupV2DirPath , O_DIRECTORY | O_RDONLY , 0 )
95- if fd < 0 {
96- return 0 , fmt .Errorf ("failed to open cgroupv2 directory path %s: %w" , cgroupV2DirPath , err )
97- }
98- return fd , nil
99- }
100-
10180func initFilters (bpfModule * bpf.Module ) {
10281 if opts .cgroup != "" {
10382 idx := 0
104- cgroupFd , err := getCgroupDirFD (opts .cgroup )
83+ cgroupFd , err := common . GetCgroupDirFD (opts .cgroup )
10584 if err != nil {
10685 log .Fatalln (err )
10786 }
@@ -135,10 +114,10 @@ func formatEvent(event BindEvent) {
135114 fmt .Printf ("%8s " , time .Now ().Format ("15:04:05" ))
136115 }
137116 switch event .Proto {
138- case IPProtoTCP :
117+ case common . IPPROTO_TCP :
139118 proto = "TCP"
140119 break
141- case IPProtoUDP :
120+ case common . IPPROTO_UDP :
142121 proto = "UDP"
143122 default :
144123 proto = "UNK"
@@ -150,16 +129,12 @@ func formatEvent(event BindEvent) {
150129 }
151130 switch event .Ver {
152131 case 4 :
153- v := [4 ]byte {}
154- for i := 0 ; i < 4 ; i ++ {
155- v [i ] = event .Addr [i ]
156- }
157- addr = netip .AddrFrom4 (v ).String ()
132+ addr = common .AddrFrom16 (common .AF_INET , event .Addr ).String ()
158133 default :
159- addr = netip .AddrFrom16 (event .Addr ).String ()
134+ addr = common .AddrFrom16 (common . AF_INET6 , event .Addr ).String ()
160135 }
161136 fmt .Printf ("%-7d %-16s %-3d %-5s %-5s %-4d %-5d %-48s\n " ,
162- event .Pid , event . TaskString ( ), event .Ret , proto , bindOpts , event .BoundDevIf , event .Port , addr )
137+ event .Pid , common . GoString ( event . Task [:] ), event .Ret , proto , bindOpts , event .BoundDevIf , event .Port , addr )
163138}
164139
165140func main () {
0 commit comments