Improve IP/Port parsing
This commit is contained in:
@@ -2,39 +2,45 @@ package netutils
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
|
||||
"github.com/safing/portmaster/network/packet"
|
||||
)
|
||||
|
||||
var errInvalidIP = errors.New("invalid IP address")
|
||||
|
||||
// IPFromAddr extracts or parses the IP address contained in the given address.
|
||||
func IPFromAddr(addr net.Addr) (net.IP, error) {
|
||||
// IPPortFromAddr extracts or parses the IP address and port contained in the given address.
|
||||
func IPPortFromAddr(addr net.Addr) (ip net.IP, port uint16, err error) {
|
||||
// Convert addr to IP if needed.
|
||||
switch v := addr.(type) {
|
||||
case *net.TCPAddr:
|
||||
return v.IP, nil
|
||||
return v.IP, uint16(v.Port), nil
|
||||
case *net.UDPAddr:
|
||||
return v.IP, nil
|
||||
return v.IP, uint16(v.Port), nil
|
||||
case *net.IPAddr:
|
||||
return v.IP, nil
|
||||
return v.IP, 0, nil
|
||||
case *net.UnixAddr:
|
||||
return nil, 0, errors.New("unix addresses don't have IPs")
|
||||
default:
|
||||
// Parse via string.
|
||||
host, _, err := net.SplitHostPort(addr.String())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to split host and port of %q: %w", addr, err)
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("address %q does not contain a valid IP address", addr)
|
||||
}
|
||||
return ip, nil
|
||||
return ParseIPPort(addr.String())
|
||||
}
|
||||
}
|
||||
|
||||
// ParseHostPort parses a <ip>:port formatted address.
|
||||
func ParseHostPort(address string) (net.IP, uint16, error) {
|
||||
// ProtocolFromNetwork returns the protocol from the given net, as used in the "net" golang stdlib.
|
||||
func ProtocolFromNetwork(net string) (protocol packet.IPProtocol) {
|
||||
switch net {
|
||||
case "tcp", "tcp4", "tcp6":
|
||||
return packet.TCP
|
||||
case "udp", "udp4", "udp6":
|
||||
return packet.UDP
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// ParseIPPort parses a <ip>:port formatted address.
|
||||
func ParseIPPort(address string) (net.IP, uint16, error) {
|
||||
ipString, portString, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
|
||||
Reference in New Issue
Block a user