Golang 获取当前外网IP

首先在外网需要设置nginx配置

  location /get_ip {            
    default_type text/plain;            
    return 200 "$remote_addr\n";        
}

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)
 
}
©版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容