### Control: Apply SO_REUSEADDR and SO_REUSEPORT Source: https://context7.com/libp2p/go-reuseport/llms.txt Low-level socket control function to apply SO_REUSEADDR and SO_REUSEPORT. Integrates with net.ListenConfig.Control and net.Dialer.Control for custom connection setup. ```go package main import ( "context" "fmt" "net" reuse "github.com/libp2p/go-reuseport" ) func main() { // Use Control directly with net.ListenConfig for custom listener setup lc := net.ListenConfig{ Control: reuse.Control, } l1, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:7777") if err != nil { panic(err) } defer l1.Close() // A second listener on the same port succeeds because Control set SO_REUSEPORT l2, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:7777") if err != nil { panic(err) } defer l2.Close() fmt.Println("Both listeners active on", l1.Addr()) // Use Control directly with net.Dialer for outbound connections nla, _ := reuse.ResolveAddr("tcp", "127.0.0.1:7777") d := net.Dialer{ Control: reuse.Control, LocalAddr: nla, } // Can dial from the same port the listener is bound to c, err := d.Dial("tcp", "127.0.0.1:8888") // some remote if err != nil { fmt.Println("dial error (expected if 8888 not listening):", err) return } defer c.Close() } ``` -------------------------------- ### ResolveAddr: Parse Network Addresses Source: https://context7.com/libp2p/go-reuseport/llms.txt Resolves address strings into net.Addr types for various networks. Supports IP, TCP, UDP, and Unix domain sockets. Useful for manual net.Dialer or net.ListenConfig setup. ```go package main import ( "fmt" "net" reuse "github.com/libp2p/go-reuseport" ) func main() { // Resolve a TCP address addr, err := reuse.ResolveAddr("tcp", "127.0.0.1:8080") if err != nil { panic(err) } fmt.Printf("network: %s, address: %s\n", addr.Network(), addr.String()) // Output: network: tcp, address: 127.0.0.1:8080 // Resolve a UDP address udpAddr, err := reuse.ResolveAddr("udp4", "0.0.0.0:5353") if err != nil { panic(err) } fmt.Printf("network: %s, address: %s\n", udpAddr.Network(), udpAddr.String()) // Output: network: udp, address: 0.0.0.0:5353 // Use with a custom net.Dialer for advanced control nla, _ := reuse.ResolveAddr("tcp", "127.0.0.1:4444") d := net.Dialer{ Control: reuse.Control, LocalAddr: nla, } conn, err := d.Dial("tcp", "127.0.0.1:5555") if err != nil { fmt.Println("dial error:", err) return } defer conn.Close() // Unknown network returns an error _, err = reuse.ResolveAddr("quic", "127.0.0.1:4433") fmt.Println("unknown network error:", err) // Output: unknown network error: unknown network quic } ``` -------------------------------- ### Dial from the Same TCP Port Source: https://github.com/libp2p/go-reuseport/blob/master/README.md Shows how to use `reuse.Dial` to establish outgoing TCP connections from a specific local port, after having set up listeners. Note that dialing oneself is not possible due to TCP/IP stack limitations. ```Go // dial from the same port. oh yeah. l1, _ := reuse.Listen("tcp", "127.0.0.1:1234") l2, _ := reuse.Listen("tcp", "127.0.0.1:1235") c, _ := reuse.Dial("tcp", "127.0.0.1:1234", "127.0.0.1:1235") ``` -------------------------------- ### Listen on the Same TCP Port Source: https://github.com/libp2p/go-reuseport/blob/master/README.md Demonstrates how to use `reuse.Listen` to open multiple listeners on the same TCP port. This is a core feature for enabling port reuse. ```Go // listen on the same port. oh yeah. l1, _ := reuse.Listen("tcp", "127.0.0.1:1234") l2, _ := reuse.Listen("tcp", "127.0.0.1:1234") ``` -------------------------------- ### Available() bool Source: https://context7.com/libp2p/go-reuseport/llms.txt Checks if SO_REUSEPORT or equivalent behavior is supported on the current operating system. Returns true on most supported platforms for API compatibility. ```APIDOC ## Available() ### Description Returns whether `SO_REUSEPORT` or equivalent behavior is supported by the current operating system. On all supported platforms (Linux, macOS, Windows, FreeBSD) this always returns `true`; on Plan 9 and WebAssembly the underlying socket options are no-ops but the function still returns `true` for API compatibility. ### Method `Available()` ### Parameters None ### Response - **bool**: `true` if SO_REUSEPORT is available, `false` otherwise. ``` -------------------------------- ### ListenPacket: UDP Listener with SO_REUSEADDR/SO_REUSEPORT Source: https://context7.com/libp2p/go-reuseport/llms.txt Creates a UDP listener with SO_REUSEADDR and SO_REUSEPORT. Suitable for DNS servers, QUIC, or other UDP-based protocols. Multiple listeners can bind to the same wildcard or explicit port. ```go package main import ( "fmt" "net" reuse "github.com/libp2p/go-reuseport" ) func main() { // Bind two UDP sockets to the same wildcard port (OS assigns the port) pc1, err := reuse.ListenPacket("udp", ":0") if err != nil { panic(err) } defer pc1.Close() // Bind to an explicit port shared with another packet conn pc2, err := reuse.ListenPacket("udp", "127.0.0.1:5555") if err != nil { panic(err) } defer pc2.Close() pc3, err := reuse.ListenPacket("udp", "127.0.0.1:5555") if err != nil { panic(err) } defer pc3.Close() fmt.Println("pc1 addr:", pc1.LocalAddr()) // e.g. [::]:54321 fmt.Println("pc2 addr:", pc2.LocalAddr()) // 127.0.0.1:5555 fmt.Println("pc3 addr:", pc3.LocalAddr()) // 127.0.0.1:5555 // Send a UDP datagram to pc2/pc3 conn, _ := net.Dial("udp", "127.0.0.1:5555") defer conn.Close() conn.Write([]byte("hello")) buf := make([]byte, 64) // One of pc2 or pc3 will receive the datagram (kernel load-balances) n, addr, _ := pc2.ReadFrom(buf) fmt.Printf("received %q from %s\n", buf[:n], addr) } ``` -------------------------------- ### Listen(network, address string) (net.Listener, error) Source: https://context7.com/libp2p/go-reuseport/llms.txt Creates a TCP listener with SO_REUSEADDR and SO_REUSEPORT socket options enabled, allowing multiple listeners on the same address and port. ```APIDOC ## Listen(network, address string) (net.Listener, error) ### Description Creates a TCP (or other stream-based) listener with `SO_REUSEADDR` and `SO_REUSEPORT` set on the underlying socket. Multiple listeners can be bound to the same address and port simultaneously, which is the key behavior that distinguishes this from `net.Listen`. The returned `net.Listener` is fully compatible with the standard library. ### Method `Listen(network, address string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **network** (string) - Required - The network protocol (e.g., "tcp"). - **address** (string) - Required - The address and port to listen on (e.g., "127.0.0.1:1234"). ### Response #### Success Response (200) - **net.Listener**: A listener object compatible with the standard library. - **error**: An error if the listener could not be created. ``` -------------------------------- ### Create TCP Listener with Port Reuse Source: https://context7.com/libp2p/go-reuseport/llms.txt Creates a TCP listener with SO_REUSEADDR and SO_REUSEPORT socket options enabled. This allows multiple listeners to bind to the same address and port, unlike the standard `net.Listen`. The returned `net.Listener` is compatible with the standard library. ```go package main import ( "fmt" "net" reuse "github.com/libp2p/go-reuseport" ) func main() { // Both listeners bind to the exact same address and port — this would // fail with "address already in use" using the standard net.Listen. l1, err := reuse.Listen("tcp", "127.0.0.1:1234") if err != nil { panic(err) } defer l1.Close() l2, err := reuse.Listen("tcp", "127.0.0.1:1234") if err != nil { panic(err) } defer l2.Close() fmt.Println("l1 address:", l1.Addr()) // 127.0.0.1:1234 fmt.Println("l2 address:", l2.Addr()) // 127.0.0.1:1234 // Accept connections on l1 in a goroutine go func() { conn, err := l1.Accept() if err != nil { return } defer conn.Close() fmt.Println("l1 accepted connection from:", conn.RemoteAddr()) }() // Accept connections on l2 in another goroutine go func() { conn, err := l2.Accept() if err != nil { return } defer conn.Close() fmt.Println("l2 accepted connection from:", conn.RemoteAddr()) }() // Standard dial will route to one of the listeners c, err := net.Dial("tcp", "127.0.0.1:1234") if err != nil { panic(err) } defer c.Close() } ``` -------------------------------- ### Check SO_REUSEPORT Availability Source: https://context7.com/libp2p/go-reuseport/llms.txt Use this function to determine if SO_REUSEPORT or equivalent behavior is supported on the current operating system. It returns true on most common platforms. ```go package main import ( "fmt" reuse "github.com/libp2p/go-reuseport" ) func main() { if reuse.Available() { fmt.Println("SO_REUSEPORT is available on this system") } else { fmt.Println("SO_REUSEPORT is NOT available on this system") } } ``` -------------------------------- ### DialTimeout: TCP Dial with Timeout for Production Source: https://context7.com/libp2p/go-reuseport/llms.txt Identical to Dial but includes a timeout for the dial attempt. Passing 0 for timeout means no timeout. Useful for preventing indefinite blocking on unreachable peers. ```go package main import ( "fmt" "time" reuse "github.com/libp2p/go-reuseport" ) func main() { // Attempt to connect from local :9000 to a non-responsive remote, // giving up after 2 seconds. conn, err := reuse.DialTimeout( "tcp", "127.0.0.1:9000", // local address "192.0.2.1:9001", // remote address (unreachable/TEST-NET) 2*time.Second, ) if err != nil { fmt.Println("dial timed out or failed:", err) return } defer conn.Close() fmt.Println("connected:", conn.RemoteAddr()) } // Output: dial timed out or failed: dial tcp 127.0.0.1:9000->192.0.2.1:9001: i/o timeout ``` -------------------------------- ### ListenPacket Source: https://context7.com/libp2p/go-reuseport/llms.txt Creates a UDP (or other packet-based) listener with SO_REUSEADDR and SO_REUSEPORT set. This function is equivalent to `Listen` but is designed for connectionless, packet-oriented protocols. It returns a `net.PacketConn` compatible with the standard library, suitable for applications like DNS servers, QUIC transports, or any other UDP-based protocol. ```APIDOC ## ListenPacket ### Description Creates a UDP (or other packet-based) listener with `SO_REUSEADDR` and `SO_REUSEPORT` set. Equivalent to `Listen` but for connectionless, packet-oriented protocols. Returns a `net.PacketConn` compatible with the standard library, suitable for use in DNS servers, QUIC transports, or any other UDP-based protocol. ### Method Signature `ListenPacket(network, address string) (net.PacketConn, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "net" reuse "github.com/libp2p/go-reuseport" ) func main() { // Bind two UDP sockets to the same wildcard port (OS assigns the port) pc1, err := reuse.ListenPacket("udp", ":0") if err != nil { panic(err) } defer pc1.Close() // Bind to an explicit port shared with another packet conn pc2, err := reuse.ListenPacket("udp", "127.0.0.1:5555") if err != nil { panic(err) } defer pc2.Close() pc3, err := reuse.ListenPacket("udp", "127.0.0.1:5555") if err != nil { panic(err) } defer pc3.Close() fmt.Println("pc1 addr:", pc1.LocalAddr()) fmt.Println("pc2 addr:", pc2.LocalAddr()) fmt.Println("pc3 addr:", pc3.LocalAddr()) // Send a UDP datagram to pc2/pc3 conn, _ := net.Dial("udp", "127.0.0.1:5555") defer conn.Close() conn.Write([]byte("hello")) buf := make([]byte, 64) // One of pc2 or pc3 will receive the datagram (kernel load-balances) n, addr, _ := pc2.ReadFrom(buf) fmt.Printf("received %q from %s\n", buf[:n], addr) } ``` ### Response #### Success Response Returns a `net.PacketConn` and an `error`. The `net.PacketConn` is a listener socket configured with `SO_REUSEADDR` and `SO_REUSEPORT`. #### Response Example (See Request Example for usage context) ``` -------------------------------- ### DialTimeout Source: https://context7.com/libp2p/go-reuseport/llms.txt Identical to `Dial` but includes a `time.Duration` timeout for the dial attempt. If the timeout is reached before the connection is established, the attempt is cancelled and an error is returned. A timeout of `0` means no timeout, behaving identically to `Dial`. This is useful for preventing indefinite blocking in production environments when dialing unreachable peers. ```APIDOC ## DialTimeout ### Description Identical to `Dial` but accepts a `time.Duration` timeout, after which the dial attempt is cancelled and an error is returned. Passing `0` as timeout means no timeout (same behavior as `Dial`). Useful in production code where dial attempts to unreachable peers should not block indefinitely. ### Method Signature `DialTimeout(network, laddr, raddr string, timeout time.Duration) (net.Conn, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "time" reuse "github.com/libp2p/go-reuseport" ) func main() { // Attempt to connect from local :9000 to a non-responsive remote, // giving up after 2 seconds. conn, err := reuse.DialTimeout( "tcp", "127.0.0.1:9000", // local address "192.0.2.1:9001", // remote address (unreachable/TEST-NET) 2*time.Second, ) if err != nil { fmt.Println("dial timed out or failed:", err) return } defer conn.Close() fmt.Println("connected:", conn.RemoteAddr()) } // Output: dial timed out or failed: dial tcp 127.0.0.1:9000->192.0.2.1:9001: i/o timeout ``` ### Response #### Success Response Returns a `net.Conn` representing the established connection and an `error`. The connection is established with `SO_REUSEADDR` and `SO_REUSEPORT` set on the local binding, and the dial attempt respects the provided timeout. #### Response Example (See Request Example for usage context) ``` -------------------------------- ### Dial: TCP Dial with SO_REUSEADDR/SO_REUSEPORT for NAT Holepunching Source: https://context7.com/libp2p/go-reuseport/llms.txt Dials a remote address while binding the outgoing connection to a specific local address with SO_REUSEADDR and SO_REUSEPORT. This is crucial for TCP NAT holepunching, allowing an outgoing connection from the same local port a listener is bound to. ```go package main import ( "fmt" "io" reuse "github.com/libp2p/go-reuseport" ) func main() { // Server side: listen on :1235 server, err := reuse.Listen("tcp", "127.0.0.1:1235") if err != nil { panic(err) } defer server.Close() go func() { conn, err := server.Accept() if err != nil { return } defer conn.Close() io.WriteString(conn, "hello from server\n") }() // Client side: listen on :1234 AND dial outbound from :1234 to :1235. // This demonstrates using the same local port for both listening and dialing. l, err := reuse.Listen("tcp", "127.0.0.1:1234") if err != nil { panic(err) } defer l.Close() // Dial from local port 1234 to remote port 1235 conn, err := reuse.Dial("tcp", "127.0.0.1:1234", "127.0.0.1:1235") if err != nil { panic(err) } defer conn.Close() data, _ := io.ReadAll(conn) fmt.Printf("received: %s", data) // Output: received: hello from server } ``` -------------------------------- ### Control Source: https://context7.com/libp2p/go-reuseport/llms.txt The low-level socket control function that applies SO_REUSEADDR and SO_REUSEPORT to a raw file descriptor. Designed for use with net.ListenConfig.Control and net.Dialer.Control. ```APIDOC ## Control Control(network, address string, c syscall.RawConn) error ### Description The low-level socket control function that applies `SO_REUSEADDR` and `SO_REUSEPORT` to a raw file descriptor. This function is the build-tag–switched implementation core of the package: on Linux/macOS/other Unix it sets both options, on FreeBSD it additionally sets `SO_REUSEPORT_LB`, on Windows it sets only `SO_REUSEADDR`, and on Plan 9/Wasm it is a no-op. It is designed for use with `net.ListenConfig.Control` and `net.Dialer.Control`, allowing integration with custom connection setup pipelines. ### Parameters #### Path Parameters - **network** (string) - Required - The network type (e.g., "tcp"). - **address** (string) - Required - The address string (e.g., "127.0.0.1:7777"). - **c** (syscall.RawConn) - Required - The raw connection to apply socket options to. ### Returns - **error**: An error if applying the socket options fails. ``` -------------------------------- ### ResolveAddr Source: https://context7.com/libp2p/go-reuseport/llms.txt Resolves a network address string into a concrete net.Addr type, supporting various network protocols. This is useful for manually constructing net.Dialer or net.ListenConfig with SO_REUSEPORT semantics. ```APIDOC ## ResolveAddr ResolveAddr(network, address string) (net.Addr, error) ### Description Resolves an address string into the appropriate `net.Addr` concrete type for the given network. Supports `ip`/`ip4`/`ip6`, `tcp`/`tcp4`/`tcp6`, `udp`/`udp4`/`udp6`, and `unix`/`unixgram`/`unixpacket` networks. Used internally by `DialTimeout`, but exposed for callers that need to construct a `net.Dialer` or `net.ListenConfig` manually with `SO_REUSEPORT` semantics. ### Parameters #### Path Parameters - **network** (string) - Required - The network type (e.g., "tcp", "udp"). - **address** (string) - Required - The address string (e.g., "127.0.0.1:8080"). ### Returns - **net.Addr**: The resolved network address. - **error**: An error if the address resolution fails or the network is unsupported. ``` -------------------------------- ### Dial Source: https://context7.com/libp2p/go-reuseport/llms.txt Dials a remote address while binding the outgoing connection to a specific local address, with `SO_REUSEADDR` and `SO_REUSEPORT` set. This function is crucial for TCP NAT holepunching, enabling a process to originate an outgoing connection from the exact same local port that a listener is already bound to. ```APIDOC ## Dial ### Description Dials a remote address while binding the outgoing connection to a specific local address, with `SO_REUSEADDR` and `SO_REUSEPORT` set. This is the critical function for TCP NAT holepunching: it allows a process to originate an outgoing connection from the exact same local port that a listener is already bound to, forming the same 4-tuple that the NAT device is tracking. ### Method Signature `Dial(network, laddr, raddr string) (net.Conn, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go package main import ( "fmt" "io" reuse "github.com/libp2p/go-reuseport" ) func main() { // Server side: listen on :1235 server, err := reuse.Listen("tcp", "127.0.0.1:1235") if err != nil { panic(err) } defer server.Close() go func() { conn, err := server.Accept() if err != nil { return } defer conn.Close() io.WriteString(conn, "hello from server\n") }() // Client side: listen on :1234 AND dial outbound from :1234 to :1235. // This demonstrates using the same local port for both listening and dialing. l, err := reuse.Listen("tcp", "127.0.0.1:1234") if err != nil { panic(err) } defer l.Close() // Dial from local port 1234 to remote port 1235 conn, err := reuse.Dial("tcp", "127.0.0.1:1234", "127.0.0.1:1235") if err != nil { panic(err) } defer conn.Close() data, _ := io.ReadAll(conn) fmt.Printf("received: %s", data) // Output: received: hello from server } ``` ### Response #### Success Response Returns a `net.Conn` representing the established connection and an `error`. The connection is established with `SO_REUSEADDR` and `SO_REUSEPORT` set on the local binding. #### Response Example (See Request Example for usage context) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.