udp_all.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package udp
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strconv"
  7. )
  8. type m map[string]interface{}
  9. type Addr struct {
  10. IP net.IP
  11. Port uint16
  12. }
  13. func NewAddr(ip net.IP, port uint16) *Addr {
  14. addr := Addr{IP: make([]byte, net.IPv6len), Port: port}
  15. copy(addr.IP, ip.To16())
  16. return &addr
  17. }
  18. func NewAddrFromString(s string) *Addr {
  19. ip, port, err := ParseIPAndPort(s)
  20. //TODO: handle err
  21. _ = err
  22. return &Addr{IP: ip.To16(), Port: port}
  23. }
  24. func (ua *Addr) Equals(t *Addr) bool {
  25. if t == nil || ua == nil {
  26. return t == nil && ua == nil
  27. }
  28. return ua.IP.Equal(t.IP) && ua.Port == t.Port
  29. }
  30. func (ua *Addr) String() string {
  31. if ua == nil {
  32. return "<nil>"
  33. }
  34. return net.JoinHostPort(ua.IP.String(), fmt.Sprintf("%v", ua.Port))
  35. }
  36. func (ua *Addr) MarshalJSON() ([]byte, error) {
  37. if ua == nil {
  38. return nil, nil
  39. }
  40. return json.Marshal(m{"ip": ua.IP, "port": ua.Port})
  41. }
  42. func (ua *Addr) Copy() *Addr {
  43. if ua == nil {
  44. return nil
  45. }
  46. nu := Addr{
  47. Port: ua.Port,
  48. IP: make(net.IP, len(ua.IP)),
  49. }
  50. copy(nu.IP, ua.IP)
  51. return &nu
  52. }
  53. type AddrSlice []*Addr
  54. func (a AddrSlice) Equal(b AddrSlice) bool {
  55. if len(a) != len(b) {
  56. return false
  57. }
  58. for i := range a {
  59. if !a[i].Equals(b[i]) {
  60. return false
  61. }
  62. }
  63. return true
  64. }
  65. func ParseIPAndPort(s string) (net.IP, uint16, error) {
  66. rIp, sPort, err := net.SplitHostPort(s)
  67. if err != nil {
  68. return nil, 0, err
  69. }
  70. addr, err := net.ResolveIPAddr("ip", rIp)
  71. if err != nil {
  72. return nil, 0, err
  73. }
  74. iPort, err := strconv.Atoi(sPort)
  75. if err != nil {
  76. return nil, 0, err
  77. }
  78. return addr.IP, uint16(iPort), nil
  79. }