HTTP Server from TCP Socket (in Go)
Problem:
Creating an HTTP server on a specific VRF interface using a custom TCP socket results in the error "accept tcp 127.0.0.1:80: accept: invalid argument."
Solution:
Injection of Socket Options Using net.ListenConfig:
To resolve this issue, use a net.ListenConfig to inject the desired socket options before calling syscall.Bind. This ensures that the socket setup is performed according to the specifications of the net package.
Steps:
Code Sample:
<code class="go">func main() { lc := net.ListenConfig{Control: controlOnConnSetup} ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:80") if err != nil { log.Fatal(err) } ln.Close() } func controlOnConnSetup(network string, address string, c syscall.RawConn) error { var operr error fn := func(fd uintptr) { operr = syscall.SetsockoptString(int(fd), syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, "vrfiface") } if err := c.Control(fn); err != nil { return err } if operr != nil { return operr } return nil }</code>
This approach allows for the addition of custom socket options before binding the socket to an IP address and port, resolving the issue encountered when creating an HTTP server on a specific VRF interface.
The above is the detailed content of How to Resolve \'Invalid Argument\' Error when Creating an HTTP Server on a Custom TCP Socket in Go?. For more information, please follow other related articles on the PHP Chinese website!