github.com/noisysockets/noisysockets@v0.21.2-0.20240515114641-7f467e651c90/networkutil/address_types.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 networkutil
    11  
    12  import (
    13  	stdnet "net"
    14  	"net/netip"
    15  )
    16  
    17  // ToNetIPAddrs converts a list of net.Addr to a list of netip.Addr.
    18  func ToNetIPAddrs(addrs []stdnet.Addr) (netipAddrs []netip.Addr, ok bool) {
    19  	netipAddrs = make([]netip.Addr, len(addrs))
    20  	for i, a := range addrs {
    21  		switch a := a.(type) {
    22  		case *stdnet.IPAddr:
    23  			if ip := a.IP.To4(); ip != nil {
    24  				netipAddrs[i], ok = netip.AddrFromSlice(ip)
    25  			} else {
    26  				netipAddrs[i], ok = netip.AddrFromSlice(a.IP)
    27  			}
    28  			if !ok {
    29  				return
    30  			}
    31  		case *stdnet.IPNet:
    32  			if ip := a.IP.To4(); ip != nil {
    33  				netipAddrs[i], ok = netip.AddrFromSlice(ip)
    34  			} else {
    35  				netipAddrs[i], ok = netip.AddrFromSlice(a.IP)
    36  			}
    37  			if !ok {
    38  				return
    39  			}
    40  		default:
    41  			return netipAddrs, false
    42  		}
    43  	}
    44  
    45  	return netipAddrs, true
    46  }