udp_all.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package nebula
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. )
  8. type udpAddr struct {
  9. IP net.IP
  10. Port uint16
  11. }
  12. func NewUDPAddr(ip net.IP, port uint16) *udpAddr {
  13. addr := udpAddr{IP: make([]byte, len(ip)), Port: port}
  14. copy(addr.IP, ip)
  15. return &addr
  16. }
  17. func NewUDPAddrFromString(s string) *udpAddr {
  18. ip, port, err := parseIPAndPort(s)
  19. //TODO: handle err
  20. _ = err
  21. return &udpAddr{IP: ip, Port: port}
  22. }
  23. func (ua *udpAddr) Equals(t *udpAddr) bool {
  24. if t == nil || ua == nil {
  25. return t == nil && ua == nil
  26. }
  27. return ua.IP.Equal(t.IP) && ua.Port == t.Port
  28. }
  29. func (ua *udpAddr) String() string {
  30. return net.JoinHostPort(ua.IP.String(), fmt.Sprintf("%v", ua.Port))
  31. }
  32. func (ua *udpAddr) MarshalJSON() ([]byte, error) {
  33. return json.Marshal(m{"ip": ua.IP, "port": ua.Port})
  34. }
  35. func (ua *udpAddr) Copy() *udpAddr {
  36. nu := udpAddr{
  37. Port: ua.Port,
  38. IP: make(net.IP, len(ua.IP)),
  39. }
  40. copy(nu.IP, ua.IP)
  41. return &nu
  42. }
  43. func parseIPAndPort(s string) (net.IP, uint16, error) {
  44. rIp, sPort, err := net.SplitHostPort(s)
  45. if err != nil {
  46. return nil, 0, err
  47. }
  48. iPort, err := strconv.Atoi(sPort)
  49. ip := net.ParseIP(rIp)
  50. return ip, uint16(iPort), nil
  51. }