登录
首页 >  Golang >  Go问答

如何在 GOLANG 中打印本地主机的 IP 地址?

来源:stackoverflow

时间:2024-02-28 12:33:25 351浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《如何在 GOLANG 中打印本地主机的 IP 地址?》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

我有这段代码,我尝试获取本地主机 ip 127.0.0.1

func (m *repostory) homehandeler(w http.responsewriter, r *http.request) {
    
    // loop over header names
    for name, values := range r.header {
        // loop over all values for the name.
        for _, value := range values {
            fmt.println(name, value)
        }
    }
    remoteip := utils.readuserip(r)
}

循环的结果:

sec-ch-ua " not a;brand";v="99", "chromium";v="102", "google chrome";v="102"
sec-ch-ua-mobile ?0
cookie csrf_token=4f7ignczbtpxwp6snm6gxxxc3qe6p9gwvcar7f3vutmrue=; session=ya0nwu4wwmh up79u9erfzuwg
accept-language en,en-us;q=0.9,he;q=0.8
connection keep-alive
cache-control max-age=0
sec-ch-ua-platform "windows"
upgrade-insecure-requests 1
user-agent mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/102.0.0.0 safari/537.36
accept text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
sec-fetch-mode navigate
sec-fetch-user ?1
accept-encoding gzip, deflate, br
sec-fetch-site none
sec-fetch-dest document

但是remoteip的结果:

[::1]:55310

正确答案


我假设您正在寻找请求者的 ip?

您应该能够使用 remoteaddr 属性来获取它。

func (m *repostory) homehandeler(w http.responsewriter, r *http.request) {
    fmt.fprintf(w, "ip: %s", r.remoteaddr)
}

或者,如果您正在查找请求传入的服务器 ip,您可以从请求的上下文中获取它。

func (m *Repostory) HomeHandeler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "IP: %s", r.Context().Value(http.LocalAddrContextKey))
}

https://pkg.go.dev/net/http#Request

好了,本文到此结束,带大家了解了《如何在 GOLANG 中打印本地主机的 IP 地址?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>