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
//go:build windows
package portscan
import (
"fmt"
"os/exec"
"strconv"
"strings"
"github.com/johnandersen777/socialweb-computer-kcp/internal/hostos"
)
func listeners() (map[int][]int, error) {
out, err := exec.Command("netstat", "-ano", "-p", "tcp").Output()
if err != nil {
return nil, fmt.Errorf("portscan: running netstat -ano to list this host's TCP listeners: "+
"%w -- every bound process this package attributes is found through that listing, so a "+
"listing that cannot be read is a scan that attributes nothing", err)
}
owners := map[int][]int{}
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) < 5 || !strings.EqualFold(fields[0], "TCP") || !strings.EqualFold(fields[3], "LISTENING") {
continue
}
at := strings.LastIndex(fields[1], ":")
if at < 0 {
continue
}
port, err := strconv.Atoi(fields[1][at+1:])
if err != nil {
continue
}
pid, err := strconv.Atoi(fields[4])
if err != nil {
continue
}
owners[port] = append(owners[port], pid)
}
return owners, nil
}
func datagramListeners() (map[int][]int, error) {
out, err := exec.Command("netstat", "-ano", "-p", "udp").Output()
if err != nil {
return nil, fmt.Errorf("portscan: running netstat -ano -p udp to list this host's bound UDP "+
"sockets: %w -- a link component holds its leased port as a datagram socket, so a "+
"listing that cannot be read is a scan that attributes no link", err)
}
owners := map[int][]int{}
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) < 4 || !strings.EqualFold(fields[0], "UDP") {
continue
}
at := strings.LastIndex(fields[1], ":")
if at < 0 {
continue
}
port, err := strconv.Atoi(fields[1][at+1:])
if err != nil {
continue
}
pid, err := strconv.Atoi(fields[len(fields)-1])
if err != nil {
continue
}
owners[port] = append(owners[port], pid)
}
return owners, nil
}
func cmdline(pid int) ([]string, error) {
return hostos.Cmdline(pid)
}