nebula/udp/udp_all.go

85 lines
1.4 KiB
Go
Raw Normal View History

package udp
2021-03-19 02:37:24 +01:00
import (
"encoding/json"
"fmt"
"net"
"strconv"
)
type m map[string]interface{}
type Addr struct {
2021-03-19 02:37:24 +01:00
IP net.IP
Port uint16
}
func NewAddr(ip net.IP, port uint16) *Addr {
addr := Addr{IP: make([]byte, net.IPv6len), Port: port}
copy(addr.IP, ip.To16())
2021-03-19 02:37:24 +01:00
return &addr
}
func NewAddrFromString(s string) *Addr {
ip, port, err := ParseIPAndPort(s)
2021-03-19 02:37:24 +01:00
//TODO: handle err
_ = err
return &Addr{IP: ip.To16(), Port: port}
2021-03-19 02:37:24 +01:00
}
func (ua *Addr) Equals(t *Addr) bool {
2021-03-19 02:37:24 +01:00
if t == nil || ua == nil {
return t == nil && ua == nil
}
return ua.IP.Equal(t.IP) && ua.Port == t.Port
}
func (ua *Addr) String() string {
2021-04-27 03:21:47 +02:00
if ua == nil {
return "<nil>"
}
2021-03-19 02:37:24 +01:00
return net.JoinHostPort(ua.IP.String(), fmt.Sprintf("%v", ua.Port))
}
func (ua *Addr) MarshalJSON() ([]byte, error) {
2021-04-27 03:21:47 +02:00
if ua == nil {
return nil, nil
}
2021-03-19 02:37:24 +01:00
return json.Marshal(m{"ip": ua.IP, "port": ua.Port})
}
func (ua *Addr) Copy() *Addr {
2021-04-27 03:21:47 +02:00
if ua == nil {
return nil
}
nu := Addr{
2021-03-19 02:37:24 +01:00
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) {
2021-03-19 02:37:24 +01:00
rIp, sPort, err := net.SplitHostPort(s)
if err != nil {
return nil, 0, err
}
addr, err := net.ResolveIPAddr("ip", rIp)
if err != nil {
return nil, 0, err
}
2021-03-19 02:37:24 +01:00
iPort, err := strconv.Atoi(sPort)
if err != nil {
return nil, 0, err
}
return addr.IP, uint16(iPort), nil
2021-03-19 02:37:24 +01:00
}