diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..86c4a3c --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/cakturk/go-netstat + +go 1.13 diff --git a/netstat/netstat.go b/netstat/netstat.go index a5c0e69..824396c 100644 --- a/netstat/netstat.go +++ b/netstat/netstat.go @@ -25,14 +25,14 @@ type SockTabEntry struct { Process *Process } -// Process holds the PID and process name to which each socket belongs +// Process holds the PID and process Name to which each socket belongs type Process struct { - pid int - name string + Pid int + Name string } func (p *Process) String() string { - return fmt.Sprintf("%d/%s", p.pid, p.name) + return fmt.Sprintf("%d/%s", p.Pid, p.Name) } // SkState type represents socket connection state diff --git a/netstat/netstat_linux.go b/netstat/netstat_linux.go index 43ab3f5..2480657 100644 --- a/netstat/netstat_linux.go +++ b/netstat/netstat_linux.go @@ -80,10 +80,10 @@ func parseIPv6(s string) (net.IP, error) { for len(s) != 0 { grp := s[0:8] u, err := strconv.ParseUint(grp, 16, 32) - binary.LittleEndian.PutUint32(ip[i:j], uint32(u)) if err != nil { return nil, err } + binary.LittleEndian.PutUint32(ip[i:j], uint32(u)) i, j = i+grpLen, j+grpLen s = s[8:] } @@ -186,7 +186,7 @@ func getProcName(s []byte) string { } func (p *procFd) iterFdDir() { - // link name is of the form socket:[5860846] + // link Name is of the form socket:[5860846] fddir := path.Join(p.base, "/fd") fi, err := ioutil.ReadDir(fddir) if err != nil { @@ -212,8 +212,10 @@ func (p *procFd) iterFdDir() { if err != nil { return } + if stat != nil { + defer stat.Close() + } n, err := stat.Read(buf[:]) - stat.Close() if err != nil { return } @@ -253,8 +255,10 @@ func doNetstat(path string, fn AcceptFn) ([]SockTabEntry, error) { if err != nil { return nil, err } + if f != nil { + defer f.Close() + } tabs, err := parseSocktab(f, fn) - f.Close() if err != nil { return nil, err } diff --git a/netstat/netstat_windows.go b/netstat/netstat_windows.go index cffeedc..635093d 100644 --- a/netstat/netstat_windows.go +++ b/netstat/netstat_windows.go @@ -123,8 +123,8 @@ func (pid WinPid) Process(snp ProcessSnapshot) *Process { return nil } return &Process{ - pid: int(pid), - name: snp.ProcPIDToName(uint32(pid)), + Pid: int(pid), + Name: snp.ProcPIDToName(uint32(pid)), } } @@ -394,7 +394,7 @@ func CreateToolhelp32Snapshot(flags uint32, pid uint32) (ProcessSnapshot, error) return ret, nil } -// ProcPIDToName translates PID to a name +// ProcPIDToName translates PID to a Name func (snp ProcessSnapshot) ProcPIDToName(pid uint32) string { var processEntry Processentry32 processEntry.Size = uint32(unsafe.Sizeof(processEntry))