diff --git a/common/common_darwin.go b/common/common_darwin.go index 6cdefb4..4d41382 100644 --- a/common/common_darwin.go +++ b/common/common_darwin.go @@ -74,7 +74,7 @@ func CallLsof(invoke Invoker, pid int32, args ...string) ([]string, error) { } out, err := invoke.Command(lsof, cmd...) if err != nil { - // if not pid found, lsof returnes code 1 + // if no pid found, lsof returnes code 1 if err.Error() == "exit status 1" && len(out) == 0 { return []string{}, nil } diff --git a/net/net_darwin.go b/net/net_darwin.go index bcf2915..b9275e8 100644 --- a/net/net_darwin.go +++ b/net/net_darwin.go @@ -109,7 +109,7 @@ func NetConnectionsPid(kind string, pid int32) ([]NetConnectionStat, error) { case "all": fallthrough case "inet": - args = append(args, "tcp") + args = append(args, "tcp", "-i", "udp") case "inet4": args = append(args, "4") case "inet6": diff --git a/net/net_freebsd.go b/net/net_freebsd.go index 7cc93a5..54dc1b5 100644 --- a/net/net_freebsd.go +++ b/net/net_freebsd.go @@ -82,8 +82,57 @@ func NetIOCounters(pernic bool) ([]NetIOCountersStat, error) { return ret, nil } -func NetConnections(kind string) ([]NetConnectionStat, error) { +// Return a list of network connections opened by a process. +func NetConnectionsPid(kind string, pid int32) ([]NetConnectionStat, error) { var ret []NetConnectionStat - return ret, common.NotImplementedError + args := []string{"-i"} + switch strings.ToLower(kind) { + default: + fallthrough + case "": + fallthrough + case "all": + fallthrough + case "inet": + args = append(args, "tcp", "-i", "udp") + case "inet4": + args = append(args, "4") + case "inet6": + args = append(args, "6") + case "tcp": + args = append(args, "tcp") + case "tcp4": + args = append(args, "4tcp") + case "tcp6": + args = append(args, "6tcp") + case "udp": + args = append(args, "udp") + case "udp4": + args = append(args, "6udp") + case "udp6": + args = append(args, "6udp") + case "unix": + return ret, common.NotImplementedError + } + + // we can not use -F filter to get all of required information at once. + r, err := common.CallLsof(invoke, pid, args...) + if err != nil { + return nil, err + } + for _, rr := range r { + if strings.HasPrefix(rr, "COMMAND") { + continue + } + n, err := parseNetLine(rr) + if err != nil { + // fmt.Println(err) // TODO: should debug print? + continue + } + + ret = append(ret, n) + } + + return ret, nil } diff --git a/net/net_linux.go b/net/net_linux.go index 6e54244..7c1d015 100644 --- a/net/net_linux.go +++ b/net/net_linux.go @@ -108,7 +108,7 @@ func NetConnectionsPid(kind string, pid int32) ([]NetConnectionStat, error) { case "all": fallthrough case "inet": - args = append(args, "tcp") + args = append(args, "tcp", "-i", "udp") case "inet4": args = append(args, "4") case "inet6":