2020-03-10 12:20:34 -07:00
|
|
|
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
|
|
|
|
// See the file LICENSE for licensing terms.
|
|
|
|
|
|
|
|
package utils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
errBadIP = errors.New("bad ip format")
|
|
|
|
)
|
|
|
|
|
|
|
|
// IPDesc ...
|
|
|
|
type IPDesc struct {
|
|
|
|
IP net.IP
|
|
|
|
Port uint16
|
|
|
|
}
|
|
|
|
|
|
|
|
// Equal ...
|
|
|
|
func (ipDesc IPDesc) Equal(otherIPDesc IPDesc) bool {
|
|
|
|
return ipDesc.Port == otherIPDesc.Port &&
|
|
|
|
ipDesc.IP.Equal(otherIPDesc.IP)
|
|
|
|
}
|
|
|
|
|
|
|
|
// PortString ...
|
|
|
|
func (ipDesc IPDesc) PortString() string {
|
|
|
|
return fmt.Sprintf(":%d", ipDesc.Port)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (ipDesc IPDesc) String() string {
|
2020-04-02 14:44:43 -07:00
|
|
|
return net.JoinHostPort(ipDesc.IP.String(), fmt.Sprintf("%d", ipDesc.Port))
|
2020-03-10 12:20:34 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
// ToIPDesc ...
|
|
|
|
func ToIPDesc(str string) (IPDesc, error) {
|
2020-04-02 14:44:43 -07:00
|
|
|
host, portStr, err := net.SplitHostPort(str)
|
|
|
|
if err != nil {
|
2020-03-10 12:20:34 -07:00
|
|
|
return IPDesc{}, errBadIP
|
|
|
|
}
|
2020-04-02 14:44:43 -07:00
|
|
|
port, err := strconv.ParseUint(portStr, 10 /*=base*/, 16 /*=size*/)
|
2020-03-10 12:20:34 -07:00
|
|
|
if err != nil {
|
2020-04-02 14:44:43 -07:00
|
|
|
// TODO: Should this return a locally defined error? (e.g. errBadPort)
|
2020-03-10 12:20:34 -07:00
|
|
|
return IPDesc{}, err
|
|
|
|
}
|
2020-04-02 14:44:43 -07:00
|
|
|
ip := net.ParseIP(host)
|
2020-03-10 12:20:34 -07:00
|
|
|
if ip == nil {
|
|
|
|
return IPDesc{}, errBadIP
|
|
|
|
}
|
|
|
|
return IPDesc{
|
|
|
|
IP: ip,
|
|
|
|
Port: uint16(port),
|
|
|
|
}, nil
|
|
|
|
}
|