utils.go 921 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 (pkt *Packet) BuildEchoRequestMessage(icmptype Type) ([]byte, error) {
  19. if pkt.Nbytes < 40 {
  20. pkt.Nbytes = 40
  21. }
  22. bs := bytes.Repeat([]byte{1}, pkt.Nbytes)
  23. pkt.SendTime = time.Now()
  24. binary.BigEndian.PutUint64(bs, uint64(pkt.SendTime.UnixNano()))
  25. binary.BigEndian.PutUint64(bs[8:], uint64(pkt.Seq))
  26. binary.BigEndian.PutUint64(bs[16:], uint64(pkt.ID))
  27. copy(bs[24:], pkt.UUID[:])
  28. body := &icmp.Echo{
  29. ID: pkt.ID % 65535,
  30. Seq: pkt.Seq % 65536,
  31. Data: bs,
  32. }
  33. msg := &icmp.Message{
  34. Type: icmptype,
  35. Code: 0,
  36. Body: body,
  37. }
  38. msgBytes, err := msg.Marshal(nil)
  39. if err != nil {
  40. return nil, err
  41. }
  42. return msgBytes, nil
  43. }