2021-03-19 09:37:24 +08:00
|
|
|
package nebula
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
type udpAddr struct {
|
|
|
|
IP net.IP
|
|
|
|
Port uint16
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewUDPAddr(ip net.IP, port uint16) *udpAddr {
|
2021-04-15 02:50:09 +08:00
|
|
|
addr := udpAddr{IP: make([]byte, net.IPv6len), Port: port}
|
|
|
|
copy(addr.IP, ip.To16())
|
2021-03-19 09:37:24 +08:00
|
|
|
return &addr
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewUDPAddrFromString(s string) *udpAddr {
|
|
|
|
ip, port, err := parseIPAndPort(s)
|
|
|
|
//TODO: handle err
|
|
|
|
_ = err
|
2021-04-15 02:50:09 +08:00
|
|
|
return &udpAddr{IP: ip.To16(), Port: port}
|
2021-03-19 09:37:24 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func (ua *udpAddr) Equals(t *udpAddr) bool {
|
|
|
|
if t == nil || ua == nil {
|
|
|
|
return t == nil && ua == nil
|
|
|
|
}
|
|
|
|
return ua.IP.Equal(t.IP) && ua.Port == t.Port
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ua *udpAddr) String() string {
|
2021-04-27 09:21:47 +08:00
|
|
|
if ua == nil {
|
|
|
|
return "<nil>"
|
|
|
|
}
|
|
|
|
|
2021-03-19 09:37:24 +08:00
|
|
|
return net.JoinHostPort(ua.IP.String(), fmt.Sprintf("%v", ua.Port))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ua *udpAddr) MarshalJSON() ([]byte, error) {
|
2021-04-27 09:21:47 +08:00
|
|
|
if ua == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
2021-03-19 09:37:24 +08:00
|
|
|
return json.Marshal(m{"ip": ua.IP, "port": ua.Port})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ua *udpAddr) Copy() *udpAddr {
|
2021-04-27 09:21:47 +08:00
|
|
|
if ua == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-03-19 09:37:24 +08:00
|
|
|
nu := udpAddr{
|
|
|
|
Port: ua.Port,
|
|
|
|
IP: make(net.IP, len(ua.IP)),
|
|
|
|
}
|
|
|
|
|
|
|
|
copy(nu.IP, ua.IP)
|
|
|
|
return &nu
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseIPAndPort(s string) (net.IP, uint16, error) {
|
|
|
|
rIp, sPort, err := net.SplitHostPort(s)
|
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
2021-04-02 10:48:41 +08:00
|
|
|
addr, err := net.ResolveIPAddr("ip", rIp)
|
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
2021-03-19 09:37:24 +08:00
|
|
|
iPort, err := strconv.Atoi(sPort)
|
2021-04-02 10:48:41 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return addr.IP, uint16(iPort), nil
|
2021-03-19 09:37:24 +08:00
|
|
|
}
|