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

     1  //go:build darwin || dragonfly || freebsd || netbsd || openbsd
     2  
     3  package bufio
     4  
     5  import (
     6  	"encoding/binary"
     7  	"net/netip"
     8  	"unsafe"
     9  
    10  	"golang.org/x/sys/unix"
    11  )
    12  
    13  func ToSockaddr(destination netip.AddrPort) (name unsafe.Pointer, nameLen uint32) {
    14  	if destination.Addr().Is4() {
    15  		sa := unix.RawSockaddrInet4{
    16  			Len:    unix.SizeofSockaddrInet4,
    17  			Family: unix.AF_INET,
    18  			Addr:   destination.Addr().As4(),
    19  		}
    20  		binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&sa.Port))[:], destination.Port())
    21  		name = unsafe.Pointer(&sa)
    22  		nameLen = unix.SizeofSockaddrInet4
    23  	} else {
    24  		sa := unix.RawSockaddrInet6{
    25  			Len:    unix.SizeofSockaddrInet6,
    26  			Family: unix.AF_INET6,
    27  			Addr:   destination.Addr().As16(),
    28  		}
    29  		binary.BigEndian.PutUint16((*[2]byte)(unsafe.Pointer(&sa.Port))[:], destination.Port())
    30  		name = unsafe.Pointer(&sa)
    31  		nameLen = unix.SizeofSockaddrInet6
    32  	}
    33  	return
    34  }