On Thu, Feb 15, 2024 at 11:30:53AM -0800, Bing wrote:
> I'm trying to implement a http server and I need to bind the underlying
> socket to a specific VRF instance so that the server only listens on that
> VRF instance. When some specific event happens, the program needs to
> shutdown the http server. I'm using syscall.SetsockoptString() and option
> "SO_BINDTODEVICE".
Pretty sure what you are doing doesn't make sense... aren't you hooking into
the wrong timing?
You need to set the socket option prior to binding, not after.
There's a more convenient interface with a syscall.RawConn than what you are
using.
The attached mod seems to work, maybe try that?
Cheers,
Reto
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/golang-nuts/h36frmpo4ecm337q7zphdqyr4aydg6fdn642gl4fpigoychuwf%40kewug6kxb2li.
package main
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"syscall"
"time"
)
func main() {
// Generate a self-signed certificate and private key
// Create a TCP listener
listenConf := net.ListenConfig{
Control: func(_ string, _ string, c syscall.RawConn) error {
var err error
cerr := c.Control(func(fd uintptr) {
err = syscall.SetsockoptString(int(fd),
syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, "eth0")
})
return errors.Join(cerr, err)
},
}
listener, err := listenConf.Listen(context.Background(), "tcp",
"localhost:443")
if err != nil {
fmt.Println("Error creating listener:", err)
return
}
// Create an HTTP server with the custom listener and TLS config
server := &http.Server{
Addr: "localhost:443",
Handler: http.HandlerFunc(handler),
}
// Start the HTTP server
go func() {
fmt.Println("Starting HTTP server with TLS...")
if err := server.Serve(listener); err != nil && err !=
http.ErrServerClosed {
fmt.Println("Error starting server:", err)
return
}
}()
// Start a timer
duration := 1 * time.Second
fmt.Printf("Timer started. Server will be closed after %s.\n", duration)
timer := time.NewTimer(duration)
// Wait for the timer to expire
<-timer.C
// Close the HTTP server gracefully
fmt.Println("Closing HTTP server...")
if err := server.Close(); err != nil {
fmt.Println("Error closing server:", err)
return
}
fmt.Println("HTTP server closed.")
}
// Handler for incoming requests
func handler(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, "Hello, HTTPS!")
}