github.com/haraldrudell/parl@v0.4.176/pnet/net-legacy.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  var _ net.Addr
    16  var _ netip.Addr
    17  var _ net.IPAddr
    18  
    19  // AddrToIPAddr returns the [net.Addr] for an [netip.Addr]
    20  //   - [net.Addr] is legacy interface for [net.Dial] using strings
    21  //   - — [net.Addr.Network] is string like “tcp”
    22  //   - — [net.Addr.String] is socket address literal like “1.2.3.4:80”
    23  //   - [netip.Addr] is binary value-literals based on integers
    24  //   - [net.IPAddr] is a legacy implementation of [net.Addr] for
    25  //     IPv4 or IPv6 addresses
    26  //   - — [net.IPAddr.Network] returns “ip”
    27  //   - — [net.IPAddr.String] returns “1.2.3.4” or “fe80::%eth0”
    28  func AddrToIPAddr(addr netip.Addr) (addrInterface net.Addr) {
    29  	if !addr.IsValid() {
    30  		panic(perrors.NewPF("invalid netip.Addr"))
    31  	}
    32  	return &net.IPAddr{IP: addr.AsSlice(), Zone: addr.Zone()}
    33  }
    34  
    35  // AddrPortToUDPAddr: Network() "udp"
    36  func AddrPortToUDPAddr(addrPort netip.AddrPort) (addrInterface net.Addr) {
    37  	IP, port, zone := SplitAddrPort(addrPort)
    38  	return &net.UDPAddr{IP: IP, Port: port, Zone: zone}
    39  }
    40  
    41  // IPAddr returns IPAddr from IP and IfIndex to IPAddr
    42  func IPAddr(IP net.IP, index IfIndex, zone string) (ipa *net.IPAddr, err error) {
    43  	ipa = &net.IPAddr{IP: IP}
    44  	if IsIPv6(IP) {
    45  		if zone != "" {
    46  			ipa.Zone = zone
    47  		} else {
    48  			ipa.Zone, _, err = index.Zone()
    49  		}
    50  	}
    51  	return
    52  }
    53  
    54  func AddrPortToUDPAddr2(addrPort netip.AddrPort) (addr *net.UDPAddr) {
    55  	IP, port, zone := SplitAddrPort(addrPort)
    56  	return &net.UDPAddr{IP: IP, Port: port, Zone: zone}
    57  }
    58  
    59  func SplitAddrPort(addrPort netip.AddrPort) (IP net.IP, port int, zone string) {
    60  	if !addrPort.IsValid() {
    61  		panic(perrors.NewPF("invalid netip.AddrPort"))
    62  	}
    63  	IP = addrPort.Addr().AsSlice()
    64  	port = int(addrPort.Port())
    65  	zone = addrPort.Addr().Zone()
    66  	return
    67  }
    68  
    69  // AddrPortToTCPAddr: Network() "tcp"
    70  func AddrPortToTCPAddr(addrPort netip.AddrPort) (addrInterface net.Addr) {
    71  	IP, port, zone := SplitAddrPort(addrPort)
    72  	return &net.TCPAddr{IP: IP, Port: port, Zone: zone}
    73  }