在Go中仅接受来自Localhost的HTTP连接? [英] Only accept HTTP connections from Localhost in Go?

查看:360
本文介绍了在Go中仅接受来自Localhost的HTTP连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的HTTP Server站在Golang中:

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();

在呼叫者不是本地主机的情况下断开连接的最佳方法是什么?目前,我正在考虑检查基础连接信息,并确保IP地址为127.0.0.1,但这在最终删除连接之前浪费了很多资源(并运行了大量Go代码).理想情况下,我可以检测Golang服务器以基于IP地址丢弃初始TCP SYN数据包,而根本不创建TCP连接(或显示此端口正在侦听).

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?

推荐答案

VonC 的注释转换为答案.

Converting VonC's comment into an answer.

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

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

他们在内部使用net.Listen.

来自 net.Listen :

对于TCP和UDP,laddr的语法为"host:port",例如 "127.0.0.1:8080".如果省略了host,如:8080",则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.

这篇关于在Go中仅接受来自Localhost的HTTP连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆