Home  >  Article  >  Backend Development  >  How to Resolve \"Invalid Argument\" Error when Creating an HTTP Server on a Custom TCP Socket in Go?

How to Resolve \"Invalid Argument\" Error when Creating an HTTP Server on a Custom TCP Socket in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-24 18:09:02833browse

How to Resolve

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:

  1. Define a net.ListenConfig with a Control function to manipulate the raw file descriptor.
  2. Use the Control function to call syscall.SetsockoptString to set the VRF interface binding.
  3. Create a listener using the ListenConfig and serve HTTP requests.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn