1// +build freebsd darwin
2
3package net
4
5import (
6	"context"
7	"strings"
8
9	"github.com/shirou/gopsutil/internal/common"
10)
11
12// Return a list of network connections opened.
13func Connections(kind string) ([]ConnectionStat, error) {
14	return ConnectionsWithContext(context.Background(), kind)
15}
16
17func ConnectionsWithContext(ctx context.Context, kind string) ([]ConnectionStat, error) {
18	return ConnectionsPid(kind, 0)
19}
20
21// Return a list of network connections opened returning at most `max`
22// connections for each running process.
23func ConnectionsMax(kind string, max int) ([]ConnectionStat, error) {
24	return ConnectionsMaxWithContext(context.Background(), kind, max)
25}
26
27func ConnectionsMaxWithContext(ctx context.Context, kind string, max int) ([]ConnectionStat, error) {
28	return []ConnectionStat{}, common.ErrNotImplementedError
29}
30
31// Return a list of network connections opened by a process.
32func ConnectionsPid(kind string, pid int32) ([]ConnectionStat, error) {
33	return ConnectionsPidWithContext(context.Background(), kind, pid)
34}
35
36func ConnectionsPidWithContext(ctx context.Context, kind string, pid int32) ([]ConnectionStat, error) {
37	var ret []ConnectionStat
38
39	args := []string{"-i"}
40	switch strings.ToLower(kind) {
41	default:
42		fallthrough
43	case "":
44		fallthrough
45	case "all":
46		fallthrough
47	case "inet":
48		args = append(args, "tcp", "-i", "udp")
49	case "inet4":
50		args = append(args, "4")
51	case "inet6":
52		args = append(args, "6")
53	case "tcp":
54		args = append(args, "tcp")
55	case "tcp4":
56		args = append(args, "4tcp")
57	case "tcp6":
58		args = append(args, "6tcp")
59	case "udp":
60		args = append(args, "udp")
61	case "udp4":
62		args = append(args, "6udp")
63	case "udp6":
64		args = append(args, "6udp")
65	case "unix":
66		args = []string{"-U"}
67	}
68
69	r, err := common.CallLsofWithContext(ctx, invoke, pid, args...)
70	if err != nil {
71		return nil, err
72	}
73	for _, rr := range r {
74		if strings.HasPrefix(rr, "COMMAND") {
75			continue
76		}
77		n, err := parseNetLine(rr)
78		if err != nil {
79
80			continue
81		}
82
83		ret = append(ret, n)
84	}
85
86	return ret, nil
87}
88
89// Return up to `max` network connections opened by a process.
90func ConnectionsPidMax(kind string, pid int32, max int) ([]ConnectionStat, error) {
91	return ConnectionsPidMaxWithContext(context.Background(), kind, pid, max)
92}
93
94func ConnectionsPidMaxWithContext(ctx context.Context, kind string, pid int32, max int) ([]ConnectionStat, error) {
95	return []ConnectionStat{}, common.ErrNotImplementedError
96}
97