2

How to create ipv6 server. ipv4 server looks like

package main

import (
    "fmt"
    "net/http"
)

func h(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Test")
}

func main() {
    http.HandleFunc("/", h)
    http.ListenAndServe(":80", nil)
}

but how to listen ipv6 in 80 port

ChunkCoder
  • 197
  • 1
  • 3
  • 11

1 Answers1

4

It already is listening on ipv6 (as well as ipv4).

func ListenAndServe(addr string, handler Handler) error {
    server := &Server{Addr: addr, Handler: handler}
    return server.ListenAndServe()
}

// ListenAndServe listens on the TCP network address srv.Addr and then
// calls Serve to handle requests on incoming connections.
// Accepted connections are configured to enable TCP keep-alives.
// If srv.Addr is blank, ":http" is used.
// ListenAndServe always returns a non-nil error.
func (srv *Server) ListenAndServe() error {
    addr := srv.Addr
    if addr == "" {
        addr = ":http"
    }
    ln, err := net.Listen("tcp", addr)
    if err != nil {
        return err
    }
    return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
}

If you want to only listen on ipv6, you can do

func ListenAndServe(addr string, handler Handler) error {
    srv := &http.Server{Addr: addr, Handler: handler}
    addr := srv.Addr
    if addr == "" {
        addr = ":http"
    }
    ln, err := net.Listen("tcp6", addr) // <--- tcp6 here
    if err != nil {
        return err
    }
    return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
}
dave
  • 62,300
  • 5
  • 72
  • 93
  • No need to go through all that, you can specify an address to listen on. If you specify a v4 address you get a v4 listener, a v6 address you get a v6 listener. – Adrian Apr 19 '18 at 20:04
  • You can, but the docs specifically recommend against it: "The address can use a host name, but this is not recommended, because it will create a listener for at most one of the host's IP addresses." – dave Apr 19 '18 at 20:10
  • I didn't suggest using a host name. – Adrian Apr 19 '18 at 20:11
  • ah, I misunderstood. – dave Apr 19 '18 at 20:11