英文:
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.Addr
或http.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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论