普通网友 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.

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

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan