在Go中只接受来自本地主机的HTTP连接吗?

huangapple go评论80阅读模式
英文:

Only accept HTTP connections from Localhost in Go?

问题

我在Golang中有一个简单的HTTP服务器:

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

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

s.ListenAndServe();

在这种情况下,最好的方法是如何断开非本地主机的连接?目前,我正在考虑检查底层连接信息,并确保IP地址为127.0.0.1,但这会浪费大量资源(并运行大量Go代码)才能最终断开连接。理想情况下,我可以通过IP地址来配置Golang服务器,以便根据IP地址丢弃初始的TCP SYN数据包,而不创建TCP连接(或者不显示该端口正在侦听)。

在这里,最清晰的解决方案是什么?

英文:

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

得分: 21

VonC的评论转换为答案。

您可以通过在http.Server.Addrhttp.ListenAndServe中设置host:port来绑定主机。

它们在内部使用net.Listen

来自net.Listen
> 对于TCP和UDP,laddr的语法是“host:port”,例如“127.0.0.1:8080”。如果省略了主机,如“:8080”,Listen将侦听所有可用接口,而不仅仅是具有给定主机地址的接口。

英文:

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.

huangapple
  • 本文由 发表于 2016年12月8日 06:43:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41028709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定