utils.go 835 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package icmp
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "net"
  6. "time"
  7. "golang.org/x/net/icmp"
  8. )
  9. func netAddrToIPAddr(a net.Addr) *net.IPAddr {
  10. switch v := a.(type) {
  11. case *net.UDPAddr:
  12. return &net.IPAddr{IP: v.IP, Zone: v.Zone}
  13. case *net.IPAddr:
  14. return v
  15. }
  16. return nil
  17. }
  18. func BuildEchoRequestMessage(id, seq, size int, icmptype Type) ([]byte, error) {
  19. if size < 24 {
  20. size = 24
  21. }
  22. bs := bytes.Repeat([]byte{1}, size)
  23. binary.BigEndian.PutUint64(bs, uint64(time.Now().UnixNano()))
  24. binary.BigEndian.PutUint64(bs[8:], uint64(seq))
  25. binary.BigEndian.PutUint64(bs[16:], uint64(id))
  26. body := &icmp.Echo{
  27. ID: id % 65535,
  28. Seq: seq % 65536,
  29. Data: bs,
  30. }
  31. msg := &icmp.Message{
  32. Type: icmptype,
  33. Code: 0,
  34. Body: body,
  35. }
  36. msgBytes, err := msg.Marshal(nil)
  37. if err != nil {
  38. return nil, err
  39. }
  40. return msgBytes, nil
  41. }