Only accept HTTP connections from Localhost in Go?

不羁的心 提交于 2019-12-05 00:21:27

问题


I have a simple HTTP Server standing up in Golang:

h := http.NewServeMux()
h.Handle("/somepath", MyHandler)

s := &http.Server{
    Addr:    "1234",
    Handler: h,
}   

s.ListenAndServe();

What is the best way to drop connections where the caller is not localhost? Currently I'm considering inspecting the underlying connection information and ensuring that the IP Address is 127.0.0.1, but this wastes a whole lot of resources (and runs through a whole bunch of Go code) before ultimately dropping the connection. Ideally, I can instrument the Golang server to drop the initial TCP SYN packet based on IP Address, and not create a TCP connection at all (or reveal that this port is listening).

What's the cleanest path forward here?


回答1:


Converting VonC's comment into an answer.

You can bind the host by setting host:port in your http.Server.Addr or http.ListenAndServe.

They use net.Listen internally.

From net.Listen :

For TCP and UDP, the syntax of laddr is "host:port", like "127.0.0.1:8080". If host is omitted, as in ":8080", Listen listens on all available interfaces instead of just the interface with the given host address.



来源:https://stackoverflow.com/questions/41028709/only-accept-http-connections-from-localhost-in-go

工具导航Map