udp_all.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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, net.IPv6len), Port: port}
  14. copy(addr.IP, ip.To16())
  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.To16(), 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. if ua == nil {
  31. return "<nil>"
  32. }
  33. return net.JoinHostPort(ua.IP.String(), fmt.Sprintf("%v", ua.Port))
  34. }
  35. func (ua *udpAddr) MarshalJSON() ([]byte, error) {
  36. if ua == nil {
  37. return nil, nil
  38. }
  39. return json.Marshal(m{"ip": ua.IP, "port": ua.Port})
  40. }
  41. func (ua *udpAddr) Copy() *udpAddr {
  42. if ua == nil {
  43. return nil
  44. }
  45. nu := udpAddr{
  46. Port: ua.Port,
  47. IP: make(net.IP, len(ua.IP)),
  48. }
  49. copy(nu.IP, ua.IP)
  50. return &nu
  51. }
  52. func parseIPAndPort(s string) (net.IP, uint16, error) {
  53. rIp, sPort, err := net.SplitHostPort(s)
  54. if err != nil {
  55. return nil, 0, err
  56. }
  57. addr, err := net.ResolveIPAddr("ip", rIp)
  58. if err != nil {
  59. return nil, 0, err
  60. }
  61. iPort, err := strconv.Atoi(sPort)
  62. if err != nil {
  63. return nil, 0, err
  64. }
  65. return addr.IP, uint16(iPort), nil
  66. }