栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从http.Request获取客户端IP地址的正确方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从http.Request获取客户端IP地址的正确方法

查看http.Request,您可以找到以下成员变量:

// HTTP defines that header names are case-insensitive.// The request parser implements this by canonicalizing the// name, making the first character and any characters// following a hyphen uppercase and the rest lowercase.//// For client requests certain headers are automatically// added and may override values in Header.//// See the documentation for the Request.Write method.Header Header// RemoteAddr allows HTTP servers and other software to record// the network address that sent the request, usually for// logging. This field is not filled in by ReadRequest and// has no defined format. The HTTP server in this package// sets RemoteAddr to an "IP:port" address before invoking a// handler.// This field is ignored by the HTTP client.RemoteAddr string

您可以

RemoteAddr
用来获取远程客户端的IP地址和端口(格式为“ IP:端口”),它是原始请求者 或最后一个代理
(例如,位于服务器前面的负载平衡器)的地址。

这就是您确定的全部。

然后,您可以研究 不区分大小写 的标头(根据上面的文档),这意味着您的所有示例都将起作用并产生相同的结果:

req.Header.Get("X-Forwarded-For") // capitalisationreq.Header.Get("x-forwarded-for") // doesn'treq.Header.Get("X-FORWARDED-FOR") // matter

这是因为内部

http.Header.Get
会为您标准化密钥。(如果要直接访问标头映射,而不要通过访问标头映射,则
Get
需要先使用http.CanonicalHeaderKey。)

最后,

"X-Forwarded-For"
可能是您想了解的领域,以便获取有关客户端IP的更多信息。但是,这很大程度上取决于远程端使用的HTTP软件,因为客户端可以根据需要将任何内容放入其中。另外,请注意,此字段的
预期 格式
是IP地址的逗号加空格分隔列表。您将需要对其进行一点解析以获取您选择的单个IP(可能是列表中的第一个IP),例如:

// Assuming format is as expectedips := strings.Split("10.0.0.1, 10.0.0.2, 10.0.0.3", ", ")for _, ip := range ips {    fmt.Println(ip)}

将产生:

10.0.0.110.0.0.210.0.0.3


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/386015.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号