mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-04 12:52:28 +08:00
feat: add IsPingConnected and IsTelnetConnected
This commit is contained in:
@@ -10,7 +10,9 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/duke-git/lancet/v2/fileutil"
|
||||
)
|
||||
@@ -245,3 +247,30 @@ func DownloadFile(filepath string, url string) error {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
// IsPingConnected checks if can ping specified host or not.
|
||||
// Play: todo
|
||||
func IsPingConnected(host string) bool {
|
||||
cmd := exec.Command("ping", host, "-c", "1", "-W", "6")
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IsTelnetConnected checks if can telnet specified host or not.
|
||||
// only support two args: args[0] is port, args[1] is user
|
||||
// Play: todo
|
||||
func IsTelnetConnected(host string, port string) bool {
|
||||
adder := host + ":" + port
|
||||
conn, err := net.DialTimeout("tcp", adder, 5*time.Second)
|
||||
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -98,7 +98,7 @@ func TestGetMacAddrs(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEncodeUrl(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsInternalIP")
|
||||
assert := internal.NewAssert(t, "TestEncodeUrl")
|
||||
|
||||
urlAddr := "http://www.lancet.com?a=1&b=[2]"
|
||||
encodedUrl, err := EncodeUrl(urlAddr)
|
||||
@@ -109,3 +109,23 @@ func TestEncodeUrl(t *testing.T) {
|
||||
expected := "http://www.lancet.com?a=1&b=%5B2%5D"
|
||||
assert.Equal(expected, encodedUrl)
|
||||
}
|
||||
|
||||
func TestIsPingConnected(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestIsPingConnected")
|
||||
|
||||
result1 := IsPingConnected("www.baidu.com")
|
||||
assert.Equal(true, result1)
|
||||
|
||||
result2 := IsPingConnected("www.!@#&&&.com")
|
||||
assert.Equal(false, result2)
|
||||
}
|
||||
|
||||
func TestTelnetConnected(t *testing.T) {
|
||||
assert := internal.NewAssert(t, "TestTelnetConnected")
|
||||
|
||||
result1 := IsTelnetConnected("www.baidu.com", "80")
|
||||
assert.Equal(true, result1)
|
||||
|
||||
result2 := IsTelnetConnected("www.baidu.com", "123")
|
||||
assert.Equal(false, result2)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user