如何创建ipv6服务器。 ipv4服务器看起来像
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)
}
但如何在80端口监听ipv6
答案 0 :(得分:2)
它已经在监听ipv6(以及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)})
}
如果您想仅在ipv6上收听,您可以
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)})
}