nodeaddr.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package krpc
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "net"
  6. "strconv"
  7. "github.com/anacrolix/torrent/bencode"
  8. )
  9. type NodeAddr struct {
  10. IP net.IP
  11. Port int
  12. }
  13. // A zero Port is taken to mean no port provided, per BEP 7.
  14. func (me NodeAddr) String() string {
  15. return net.JoinHostPort(me.IP.String(), strconv.FormatInt(int64(me.Port), 10))
  16. }
  17. func (me *NodeAddr) UnmarshalBinary(b []byte) error {
  18. me.IP = make(net.IP, len(b)-2)
  19. copy(me.IP, b[:len(b)-2])
  20. me.Port = int(binary.BigEndian.Uint16(b[len(b)-2:]))
  21. return nil
  22. }
  23. func (me *NodeAddr) UnmarshalBencode(b []byte) (err error) {
  24. var _b []byte
  25. err = bencode.Unmarshal(b, &_b)
  26. if err != nil {
  27. return
  28. }
  29. return me.UnmarshalBinary(_b)
  30. }
  31. func (me NodeAddr) MarshalBinary() ([]byte, error) {
  32. var b bytes.Buffer
  33. b.Write(me.IP)
  34. binary.Write(&b, binary.BigEndian, uint16(me.Port))
  35. return b.Bytes(), nil
  36. }
  37. func (me NodeAddr) MarshalBencode() ([]byte, error) {
  38. return bencodeBytesResult(me.MarshalBinary())
  39. }
  40. func (me NodeAddr) UDP() *net.UDPAddr {
  41. return &net.UDPAddr{
  42. IP: me.IP,
  43. Port: me.Port,
  44. }
  45. }
  46. func (me *NodeAddr) FromUDPAddr(ua *net.UDPAddr) {
  47. me.IP = ua.IP
  48. me.Port = ua.Port
  49. }
  50. func (me NodeAddr) Equal(x NodeAddr) bool {
  51. return me.IP.Equal(x.IP) && me.Port == x.Port
  52. }