微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

linux – 只接受Go中Localhost的HTTP连接?

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

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

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

s.ListenAndServe();

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

这里最干净的道路是什么?

解决方法

VonC评论转换为答案.

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

他们在内部使用net.Listen.

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.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐