Skip to content

Commit

Permalink
fix goroutine leak if target host is not reachable
Browse files Browse the repository at this point in the history
  * close `socket` when ping timeout is reached
  * this triggers the goroutine shutdown

fixes #4
  • Loading branch information
j-keck committed Mar 29, 2020
1 parent d6c0b7d commit 1a9d8d0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
3 changes: 2 additions & 1 deletion arping.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func PingOverIface(dstIP net.IP, iface net.Interface) (net.HardwareAddr, time.Du
duration time.Duration
err error
}
pingResultChan := make(chan PingResult)
pingResultChan := make(chan PingResult, 1)

go func() {
// send arp request
Expand Down Expand Up @@ -162,6 +162,7 @@ func PingOverIface(dstIP net.IP, iface net.Interface) (net.HardwareAddr, time.Du
case pingResult := <-pingResultChan:
return pingResult.mac, pingResult.duration, pingResult.err
case <-time.After(timeout):
deinitialize()
return nil, 0, ErrTimeout
}
}
Expand Down
34 changes: 34 additions & 0 deletions arping_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"testing"
"net"
"strings"
"time"
"runtime"
)


Expand Down Expand Up @@ -51,6 +53,38 @@ func TestGratuitousArpWithV6IP(t *testing.T) {
validateInvalidV4AddrErr(t, err)
}

func TestGoroutinesDoesNotLeak(t *testing.T) {
ip := net.ParseIP("127.0.0.1")
SetTimeout(time.Duration(10 * time.Millisecond))

spawnNumGoroutines := 5
for i := 0; i < spawnNumGoroutines; i++ {
_, _, err := Ping(ip)
if err != ErrTimeout {
t.Fatalf("timeout error expected, but not received - received err: %v", err)
}
}

ok := make(chan bool, 1)
go func(){
for {
if runtime.NumGoroutine() < spawnNumGoroutines {
ok <- true
return
}
time.Sleep(100 * time.Millisecond)
}
}()

select {
case <-ok:
// ok
case <-time.After(30 * time.Second):
t.Fatalf("timeout waiting for goroutine cleanup - num goroutines: %d",
runtime.NumGoroutine())
}
}

func validateInvalidV4AddrErr(t *testing.T, err error) {
if ! strings.Contains(err.Error(), "not a valid v4 Address") {
t.Errorf("unexpected error: %s", err)
Expand Down

0 comments on commit 1a9d8d0

Please sign in to comment.