github.com/MetalBlockchain/metalgo@v1.11.9/utils/ips/ip.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package ips
     5  
     6  import "net/netip"
     7  
     8  // IsPublic returns true if the provided address is considered to be a public
     9  // IP.
    10  func IsPublic(addr netip.Addr) bool {
    11  	return addr.IsGlobalUnicast() && !addr.IsPrivate()
    12  }
    13  
    14  // ParseAddr returns the IP address from the provided string. If the string
    15  // represents an IPv4 address in an IPv6 address, the IPv4 address is returned.
    16  func ParseAddr(s string) (netip.Addr, error) {
    17  	addr, err := netip.ParseAddr(s)
    18  	if err != nil {
    19  		return netip.Addr{}, err
    20  	}
    21  	if addr.Is4In6() {
    22  		addr = addr.Unmap()
    23  	}
    24  	return addr, nil
    25  }
    26  
    27  // ParseAddrPort returns the IP:port address from the provided string. If the
    28  // string represents an IPv4 address in an IPv6 address, the IPv4 address is
    29  // returned.
    30  func ParseAddrPort(s string) (netip.AddrPort, error) {
    31  	addrPort, err := netip.ParseAddrPort(s)
    32  	if err != nil {
    33  		return netip.AddrPort{}, err
    34  	}
    35  	addr := addrPort.Addr()
    36  	if addr.Is4In6() {
    37  		addrPort = netip.AddrPortFrom(
    38  			addr.Unmap(),
    39  			addrPort.Port(),
    40  		)
    41  	}
    42  	return addrPort, nil
    43  }
    44  
    45  // AddrFromSlice returns the IP address from the provided byte slice. If the
    46  // byte slice represents an IPv4 address in an IPv6 address, the IPv4 address is
    47  // returned.
    48  func AddrFromSlice(b []byte) (netip.Addr, bool) {
    49  	addr, ok := netip.AddrFromSlice(b)
    50  	if !ok {
    51  		return netip.Addr{}, false
    52  	}
    53  	if addr.Is4In6() {
    54  		addr = addr.Unmap()
    55  	}
    56  	return addr, true
    57  }