-
Notifications
You must be signed in to change notification settings - Fork 52
/
gonetstat.go
298 lines (236 loc) · 6.8 KB
/
gonetstat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
/*
Simple Netstat implementation.
Get data from /proc/net/tcp and /proc/net/udp and
and parse /proc/[0-9]/fd/[0-9].
Author: Rafael Santos <[email protected]>
*/
package GOnetstat
import (
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
)
const (
PROC_TCP = "/proc/net/tcp"
PROC_UDP = "/proc/net/udp"
PROC_TCP6 = "/proc/net/tcp6"
PROC_UDP6 = "/proc/net/udp6"
)
var STATE = map[string]string {
"01": "ESTABLISHED",
"02": "SYN_SENT",
"03": "SYN_RECV",
"04": "FIN_WAIT1",
"05": "FIN_WAIT2",
"06": "TIME_WAIT",
"07": "CLOSE",
"08": "CLOSE_WAIT",
"09": "LAST_ACK",
"0A": "LISTEN",
"0B": "CLOSING",
}
type Process struct {
User string
Name string
Pid string
Exe string
State string
Ip string
Port int64
ForeignIp string
ForeignPort int64
}
type iNode struct {
path string
link string
}
func getData(t string) []string {
// Get data from tcp or udp file.
var proc_t string
if t == "tcp" {
proc_t = PROC_TCP
} else if t == "udp" {
proc_t = PROC_UDP
} else if t == "tcp6" {
proc_t = PROC_TCP6
} else if t == "udp6" {
proc_t = PROC_UDP6
} else {
fmt.Printf("%s is a invalid type, tcp and udp only!\n", t)
os.Exit(1)
}
data, err := ioutil.ReadFile(proc_t)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
lines := strings.Split(string(data), "\n")
// Return lines without Header line and blank line on the end
return lines[1:len(lines) - 1]
}
func hexToDec(h string) int64 {
// convert hexadecimal to decimal.
d, err := strconv.ParseInt(h, 16, 32)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return d
}
func convertIp(ip string) string {
// Convert the ipv4 to decimal. Have to rearrange the ip because the
// default value is in little Endian order.
var out string
// Check ip size if greater than 8 is a ipv6 type
if len(ip) > 8 {
i := []string{ ip[30:32],
ip[28:30],
ip[26:28],
ip[24:26],
ip[22:24],
ip[20:22],
ip[18:20],
ip[16:18],
ip[14:16],
ip[12:14],
ip[10:12],
ip[8:10],
ip[6:8],
ip[4:6],
ip[2:4],
ip[0:2]}
out = fmt.Sprintf("%v%v:%v%v:%v%v:%v%v:%v%v:%v%v:%v%v:%v%v",
i[14], i[15], i[13], i[12],
i[10], i[11], i[8], i[9],
i[6], i[7], i[4], i[5],
i[2], i[3], i[0], i[1])
} else {
i := []int64{ hexToDec(ip[6:8]),
hexToDec(ip[4:6]),
hexToDec(ip[2:4]),
hexToDec(ip[0:2]) }
out = fmt.Sprintf("%v.%v.%v.%v", i[0], i[1], i[2], i[3])
}
return out
}
func findPid(inode string, inodes *[]iNode) string {
// Loop through all fd dirs of process on /proc to compare the inode and
// get the pid.
pid := "-"
re := regexp.MustCompile(inode)
for _, item := range *inodes {
out := re.FindString(item.link)
if len(out) != 0 {
pid = strings.Split(item.path, "/")[2]
}
}
return pid
}
func getProcessExe(pid string) string {
exe := fmt.Sprintf("/proc/%s/exe", pid)
path, _ := os.Readlink(exe)
return path
}
func getProcessName(exe string) string {
n := strings.Split(exe, "/")
name := n[len(n) -1]
return strings.Title(name)
}
func getUser(uid string) string {
u, err := user.LookupId(uid)
if err != nil {
return "Unknown"
}
return u.Username
}
func removeEmpty(array []string) []string {
// remove empty data from line
var new_array [] string
for _, i := range(array) {
if i != "" {
new_array = append(new_array, i)
}
}
return new_array
}
func processNetstatLine(line string, fileDescriptors *[]iNode, output chan<- Process) {
line_array := removeEmpty(strings.Split(strings.TrimSpace(line), " "))
ip_port := strings.Split(line_array[1], ":")
ip := convertIp(ip_port[0])
port := hexToDec(ip_port[1])
// foreign ip and port
fip_port := strings.Split(line_array[2], ":")
fip := convertIp(fip_port[0])
fport := hexToDec(fip_port[1])
state := STATE[line_array[3]]
uid := getUser(line_array[7])
pid := findPid(line_array[9], fileDescriptors)
exe := getProcessExe(pid)
name := getProcessName(exe)
output <- Process{uid, name, pid, exe, state, ip, port, fip, fport}
}
func getFileDescriptors() []string {
d, err := filepath.Glob("/proc/[0-9]*/fd/[0-9]*")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
return d
}
func getInodes() []iNode {
fileDescriptors := getFileDescriptors()
inodes := make([]iNode, len(fileDescriptors))
res := make(chan iNode, len(fileDescriptors))
go func(fileDescriptors *[]string, output chan<-iNode) {
for _, item := range *fileDescriptors {
link, _ := os.Readlink(item)
output <- iNode{item, link}
}
}(&fileDescriptors, res)
for _, _ = range fileDescriptors {
inode := <- res
inodes = append(inodes, inode)
}
return inodes
}
func netstat(t string) []Process {
// Return a array of Process with Name, Ip, Port, State .. etc
// Require Root acess to get information about some processes.
data := getData(t)
Processes := make([]Process, len(data))
res := make(chan Process, len(data))
inodes := getInodes()
for _, line := range data {
go processNetstatLine(line, &inodes, res)
}
for i, _ := range data {
p := <- res
Processes[i] = p
}
return Processes
}
func Tcp() []Process {
// Get a slice of Process type with TCP data
data := netstat("tcp")
return data
}
func Udp() []Process {
// Get a slice of Process type with UDP data
data := netstat("udp")
return data
}
func Tcp6() []Process {
// Get a slice of Process type with TCP6 data
data := netstat("tcp6")
return data
}
func Udp6() []Process {
// Get a slice of Process type with UDP6 data
data := netstat("udp6")
return data
}