普通网友 2016-12-07 22:43
浏览 104
已采纳

在Go中仅接受来自Localhost的HTTP连接?

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条回答 默认 最新

  • douwei6478 2016-12-08 07:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器