github.com/noisysockets/noisysockets@v0.21.2-0.20240515114641-7f467e651c90/internal/util/addresses.go (about)

     1  // SPDX-License-Identifier: MPL-2.0
     2  /*
     3   * Copyright (C) 2024 The Noisy Sockets Authors.
     4   *
     5   * This Source Code Form is subject to the terms of the Mozilla Public
     6   * License, v. 2.0. If a copy of the MPL was not distributed with this
     7   * file, You can obtain one at http://mozilla.org/MPL/2.0/.
     8   */
     9  
    10  package util
    11  
    12  import (
    13  	"fmt"
    14  	stdnet "net"
    15  	"net/netip"
    16  )
    17  
    18  // ParseAddrList parses a list of IP address strings and returns a list of netip.Addr.
    19  func ParseAddrList(addrList []string) ([]netip.Addr, error) {
    20  	var addrs []netip.Addr
    21  	for _, ip := range addrList {
    22  		addr, err := netip.ParseAddr(ip)
    23  		if err != nil {
    24  			return nil, fmt.Errorf("could not parse address: %w", err)
    25  		}
    26  
    27  		addrs = append(addrs, addr)
    28  	}
    29  
    30  	return addrs, nil
    31  }
    32  
    33  // ParseAddrPortList parses a list of IP address and port strings and returns a list of netip.AddrPort.
    34  func ParseAddrPortList(addrPortList []string) ([]netip.AddrPort, error) {
    35  	var addrPorts []netip.AddrPort
    36  	for _, ipPort := range addrPortList {
    37  		var addrPort netip.AddrPort
    38  
    39  		// Do we have a port specified?
    40  		if _, _, err := stdnet.SplitHostPort(ipPort); err == nil {
    41  			addrPort, err = netip.ParseAddrPort(ipPort)
    42  			if err != nil {
    43  				return nil, fmt.Errorf("could not parse address: %w", err)
    44  			}
    45  		} else {
    46  			addr, err := netip.ParseAddr(ipPort)
    47  			if err != nil {
    48  				return nil, fmt.Errorf("could not parse address: %w", err)
    49  			}
    50  
    51  			addrPort = netip.AddrPortFrom(addr, 0)
    52  		}
    53  
    54  		addrPorts = append(addrPorts, addrPort)
    55  	}
    56  
    57  	return addrPorts, nil
    58  }