1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| func Tracert(addr string) error { timeout := time.Second * 10
conn, err := icmp.ListenPacket("ip4:icmp", "0.0.0.0") if err != nil { return fmt.Errorf("error listening for ICMP packets: %w", err) } defer conn.Close()
destinationAddress, err := net.ResolveIPAddr("ip4", addr) if err != nil { return fmt.Errorf("error resolving hostname: %w", err) } fmt.Printf("Traceroute to '%s' [%s]\n", addr, destinationAddress.IP)
message := icmp.Message{ Type: ipv4.ICMPTypeEcho, Code: 0, Body: &icmp.Echo{ ID: os.Getpid() & 0xffff, Data: []byte("hello"), }, }
for ttl := 1; ttl <= 30; ttl++ { fmt.Printf("%d ", ttl)
message.Body.(*icmp.Echo).Seq = ttl
messageBytes, err := message.Marshal(nil) if err != nil { return fmt.Errorf("error marshaling ICMP message: %w", err) }
if err := conn.IPv4PacketConn().SetTTL(ttl); err != nil { return fmt.Errorf("error setting TTL: %w", err) }
start := time.Now() if _, err := conn.WriteTo(messageBytes, destinationAddress); err != nil { return fmt.Errorf("error sending ICMP packet: %w", err) }
responseBytes := make([]byte, 1500) conn.SetReadDeadline(time.Now().Add(timeout)) n, remoteAddress, err := conn.ReadFrom(responseBytes) if err != nil { if neterr, ok := err.(net.Error); ok && neterr.Timeout() { fmt.Println("* (Timeout)") } else { fmt.Println("* (Error)") } continue }
duration := time.Since(start) responseMessage, err := icmp.ParseMessage(ipv4.ICMPTypeEchoReply.Protocol(), responseBytes[:n]) if err != nil { return fmt.Errorf("error parsing ICMP message: %w", err) }
switch responseMessage.Type { case ipv4.ICMPTypeTimeExceeded: fmt.Printf("%v %v ms\n", remoteAddress, duration.Milliseconds()) case ipv4.ICMPTypeEchoReply: fmt.Printf("%v %v ms\n", remoteAddress, duration.Milliseconds()) fmt.Println("Traceroute Complete.") return nil default: return fmt.Errorf("unexpected ICMP message type: %v, code: %v", responseMessage.Type, responseMessage.Code) } }
return nil }
|