github.com/slackhq/nebula@v1.9.0/udp/udp_all.go (about)

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