Skip to content

Instantly share code, notes, and snippets.

@jakubgs
Created November 8, 2019 08:58
Show Gist options
  • Select an option

  • Save jakubgs/f12e395ee97357c45a3a5408445dd393 to your computer and use it in GitHub Desktop.

Select an option

Save jakubgs/f12e395ee97357c45a3a5408445dd393 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"log"
"net"
"os"
"time"
"golang.org/x/mobile/app"
"golang.org/x/net/icmp"
"golang.org/x/net/ipv4"
)
var addresses = []string{
"206.189.243.162:443",
"35.188.19.210:443",
"47.91.156.93:443",
}
const ProtocolICMP int = 1
func Ping(address string) error {
//c, err := icmp.ListenPacket("udp4", "0.0.0.0")
c, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0")
if err != nil {
return err
}
defer c.Close()
// Resolve any DNS (if used) and get the real IP of the target
dst, err := net.ResolveIPAddr("ip4", address)
if err != nil {
return err
}
// Make a new ICMP message
m := icmp.Message{
Type: ipv4.ICMPTypeEcho, Code: 0,
Body: &icmp.Echo{
ID: os.Getpid() & 0xffff, Seq: 1, //<< uint(seq), // TODO
Data: []byte(""),
},
}
b, err := m.Marshal(nil)
if err != nil {
return err
}
// Send it
log.Println("Dst:", dst)
n, err := c.WriteTo(b, dst)
if err != nil {
return err
} else if n != len(b) {
return errors.New(fmt.Sprintf("got %v; want %v", n, len(b)))
}
// Wait for a reply
reply := make([]byte, 1500)
err = c.SetReadDeadline(time.Now().Add(10 * time.Second))
if err != nil {
return err
}
n, peer, err := c.ReadFrom(reply)
if err != nil {
return err
}
// Pack it up boys, we're done here
rm, err := icmp.ParseMessage(ProtocolICMP, reply[:n])
if err != nil {
return err
}
switch rm.Type {
case ipv4.ICMPTypeEchoReply:
return nil
default:
return errors.New(fmt.Sprintf("got %+v, wanted echo reply from %v", rm, peer))
}
}
func main() {
app.Main(appMain)
}
func appMain(a app.App) {
log.SetPrefix("ICMP_PING: ")
var i int
for i = 0; i < len(addresses); i++ {
err := Ping(addresses[i])
if err != nil {
log.Print("Err:", err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment