update go mod and improve icmp result

master
兔子 2 years ago
parent b92288bbc9
commit be3df9703e

@ -22,6 +22,7 @@ const (
HEADER_FORM_URLENCODE = `application/x-www-form-urlencoded`
HEADER_FORM_DATA = `multipart/form-data`
HEADER_JSON = `application/json`
HEADER_PLAIN = `text/plain`
)
type RequestFile struct {

@ -33,6 +33,7 @@ func getICMP(seq uint16) ICMP {
func sendICMPRequest(icmp ICMP, destAddr *net.IPAddr, timeout time.Duration) (PingResult, error) {
var res PingResult
res.RemoteIP = destAddr.String()
conn, err := net.DialIP("ip:icmp", nil, destAddr)
if err != nil {
return res, err
@ -84,6 +85,7 @@ func checkSum(data []byte) uint16 {
type PingResult struct {
Duration time.Duration
RecvCount int
RemoteIP string
}
func Ping(ip string, seq int, timeout time.Duration) (PingResult, error) {
@ -95,3 +97,14 @@ func Ping(ip string, seq int, timeout time.Duration) (PingResult, error) {
icmp := getICMP(uint16(seq))
return sendICMPRequest(icmp, ipAddr, timeout)
}
func IsIpPingable(ip string, timeout time.Duration, retryLimit int) bool {
for i := 0; i < retryLimit; i++ {
_, err := Ping(ip, 29, timeout)
if err != nil {
continue
}
return true
}
return false
}

@ -7,5 +7,9 @@ import (
)
func Test_Ping(t *testing.T) {
fmt.Println(Ping("baidu.com", 0, time.Second*2))
fmt.Println(Ping("baidu.com", 29, time.Second*2))
fmt.Println(Ping("www.b612.me", 29, time.Second*2))
fmt.Println(IsIpPingable("baidu.com", time.Second*2, 3))
fmt.Println(IsIpPingable("www.b612.me", time.Second*2, 3))
}

Loading…
Cancel
Save