github.com/sagernet/sing@v0.4.0-beta.19.0.20240518125136-f67a0988a636/common/network/addr.go (about)

     1  package network
     2  
     3  import (
     4  	"net"
     5  	"net/netip"
     6  
     7  	"github.com/sagernet/sing/common"
     8  	M "github.com/sagernet/sing/common/metadata"
     9  )
    10  
    11  func LocalAddrs() ([]netip.Addr, error) {
    12  	interfaceAddrs, err := net.InterfaceAddrs()
    13  	if err != nil {
    14  		return nil, err
    15  	}
    16  	return common.Map(interfaceAddrs, M.AddrFromNet), nil
    17  }
    18  
    19  func IsPublicAddr(addr netip.Addr) bool {
    20  	return !(addr.IsPrivate() ||
    21  		addr.IsLoopback() ||
    22  		addr.IsMulticast() ||
    23  		addr.IsLinkLocalUnicast() ||
    24  		addr.IsInterfaceLocalMulticast() ||
    25  		addr.IsUnspecified())
    26  }
    27  
    28  func IsVirtual(addr netip.Addr) bool {
    29  	return addr.IsLoopback() || addr.IsMulticast() || addr.IsInterfaceLocalMulticast()
    30  }
    31  
    32  func LocalPublicAddrs() ([]netip.Addr, error) {
    33  	publicAddrs, err := LocalAddrs()
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	return common.Filter(publicAddrs, IsPublicAddr), nil
    38  }