github.com/haraldrudell/parl@v0.4.176/pnet/addr-port.go (about)

     1  /*
     2  © 2020–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pnet
     7  
     8  import (
     9  	"net"
    10  	"net/netip"
    11  
    12  	"github.com/haraldrudell/parl/perrors"
    13  )
    14  
    15  // AddrPortFromAddr converts tcp-protocol string-based [net.Addr]
    16  // to binary [netip.AddrPort]
    17  //   - addr should be [net.Addr] for tcp-network address
    18  //     implemented by [net.TCPAddr]
    19  //   - [netip.AddrPort] is a binary-coded socket address
    20  //   - [net.Addr] is legacy for [net.Dial] using strings for Network and
    21  //     socket address
    22  //   - [net.TCPAddr] returns
    23  //   - — Network “tcp”
    24  //   - — String like “[fe80::%eth0]:80”
    25  func AddrPortFromAddr(addr net.Addr) (near netip.AddrPort, err error) {
    26  	// Addr is interface { Network() String() }
    27  	//	- runtime type is *net.TCPAddr struct { IP IP; Port int; Zone string }
    28  	var a, ok = addr.(*net.TCPAddr)
    29  	if !ok {
    30  		err = perrors.ErrorfPF("listener.Addr runtime type not *net.TCPAddr: %T", addr)
    31  		return
    32  	}
    33  	var b netip.Addr
    34  	if b, ok = netip.AddrFromSlice(a.IP); !ok {
    35  		err = perrors.ErrorfPF("listener.Addr bad length: %d", len(a.IP))
    36  		return
    37  	} else if a.Zone != "" {
    38  		b = b.WithZone(a.Zone)
    39  	}
    40  	near = netip.AddrPortFrom(b, uint16(a.Port))
    41  
    42  	return
    43  }