Golang 获取当前外网IP/地址/运营商 - Go语言中文网 - Golang中文社区
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
responseClient, errClient := http.Get("http://ip.dhcp.cn/?ip") // 获取外网 IP
if errClient != nil {
fmt.Printf("获取外网 IP 失败,请检查网络\n")
panic(errClient)
}
// 程序在使用完 response 后必须关闭 response 的主体。
defer responseClient.Body.Close()
body, _ := ioutil.ReadAll(responseClient.Body)
clientIP := fmt.Sprintf("%s", string(body))
print(clientIP)
}
nginx配置
获取外网IP的ngnix配置:
在 nginx 中添加:
location /get_ip {
default_type text/plain;
return 200 "$remote_addr\n";
}
使用Go语言和Nginx获取外网IP

本文介绍了如何用Go语言编写程序获取外网IP,并展示了在Nginx服务器上配置获取外网IP的方法。通过访问特定URL,可以返回客户端的远程IP地址。
最低0.47元/天 解锁文章
5万+

被折叠的 条评论
为什么被折叠?



