From 6177ec7fafb7281a1945e63633ec580831e02abf Mon Sep 17 00:00:00 2001 From: hossinasaadi Date: Tue, 3 Oct 2023 15:53:02 +0400 Subject: [PATCH] add bindAddr for darwin --- transport/internet/sockopt_darwin.go | 32 ++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/transport/internet/sockopt_darwin.go b/transport/internet/sockopt_darwin.go index d8724c77..de405538 100644 --- a/transport/internet/sockopt_darwin.go +++ b/transport/internet/sockopt_darwin.go @@ -165,7 +165,7 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) } } } - + if config.TcpKeepAliveIdle > 0 || config.TcpKeepAliveInterval > 0 { if config.TcpKeepAliveIdle > 0 { if err := unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_KEEPALIVE, int(config.TcpKeepAliveInterval)); err != nil { @@ -191,14 +191,42 @@ func applyInboundSocketOptions(network string, fd uintptr, config *SocketConfig) } func bindAddr(fd uintptr, address []byte, port uint32) error { - return nil + setReuseAddr(fd) + setReusePort(fd) + + var sockaddr unix.Sockaddr + + switch len(address) { + case net.IPv4len: + a4 := &unix.SockaddrInet4{ + Port: int(port), + } + copy(a4.Addr[:], address) + sockaddr = a4 + case net.IPv6len: + a6 := &unix.SockaddrInet6{ + Port: int(port), + } + copy(a6.Addr[:], address) + sockaddr = a6 + default: + return newError("unexpected length of ip") + } + + return unix.Bind(int(fd), sockaddr) } func setReuseAddr(fd uintptr) error { + if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1); err != nil { + return newError("failed to set SO_REUSEADDR").Base(err).AtWarning() + } return nil } func setReusePort(fd uintptr) error { + if err := unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1); err != nil { + return newError("failed to set SO_REUSEPORT").Base(err).AtWarning() + } return nil } func getInterfaceIndexByName(name string) int {