diff --git a/core/commands/ping.go b/core/commands/ping.go index 5d48f260ac3..6a88df108ca 100644 --- a/core/commands/ping.go +++ b/core/commands/ping.go @@ -3,6 +3,7 @@ package commands import ( "bytes" "context" + "errors" "fmt" "io" "strings" @@ -26,6 +27,9 @@ type PingResult struct { Text string } +// ErrPingSelf is returned when the user attempts to ping themself. +var ErrPingSelf = errors.New("error: can't ping self") + var PingCmd = &cmds.Command{ Helptext: cmdkit.HelpText{ Tagline: "Send echo request packets to IPFS hosts.", @@ -80,7 +84,12 @@ trip latency information. addr, peerID, err := ParsePeerParam(req.Arguments()[0]) if err != nil { - res.SetError(err, cmdkit.ErrNormal) + res.SetError(fmt.Errorf("failed to parse peer address '%s': %s", req.Arguments()[0], err), cmdkit.ErrNormal) + return + } + + if peerID == n.Identity { + res.SetError(ErrPingSelf, cmdkit.ErrNormal) return } @@ -94,6 +103,10 @@ trip latency information. return } + if numPings <= 0 { + res.SetError(fmt.Errorf("error: ping count must be greater than 0, was %d", numPings), cmdkit.ErrNormal) + } + outChan := pingPeer(ctx, n, peerID, numPings) res.SetOutput(outChan) }, diff --git a/test/sharness/t0041-ping.sh b/test/sharness/t0041-ping.sh new file mode 100755 index 00000000000..44949f75e91 --- /dev/null +++ b/test/sharness/t0041-ping.sh @@ -0,0 +1,40 @@ +#!/bin/sh + +test_description="Test ping command" + +. lib/test-lib.sh + +test_init_ipfs + +# start iptb + wait for peering +test_expect_success 'init iptb' ' + iptb init -n 2 --bootstrap=none --port=0 +' + +startup_cluster 2 + +test_expect_success 'peer ids' ' + PEERID_0=$(iptb get id 0) && + PEERID_1=$(iptb get id 1) +' + +test_expect_success "test ping other" ' + ipfsi 0 ping -n2 -- "$PEERID_1" && + ipfsi 1 ping -n2 -- "$PEERID_0" +' + +test_expect_success "test ping self" ' + ! ipfsi 0 ping -n2 -- "$PEERID_0" && + ! ipfsi 1 ping -n2 -- "$PEERID_1" +' + +test_expect_success "test ping 0" ' + ! ipfsi 0 ping -n0 -- "$PEERID_1" && + ! ipfsi 1 ping -n0 -- "$PEERID_0" +' + +test_expect_success 'stop iptb' ' + iptb stop +' + +test_done