Golang 服务器返回公网地址
Posted wang-li
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang 服务器返回公网地址相关的知识,希望对你有一定的参考价值。
gitee地址: https://gitee.com/wang_li/ReturnOutIP
代码
package main import ( "flag" "fmt" "log" "net/http" "os" "strings" "time" ) var ( h bool LitenAddr string ListenRoute string ) func init() flag.BoolVar(&h,"h",false,"This help") flag.StringVar(&LitenAddr,"ListenAddr","0.0.0.0:93","Set http server listen address") flag.StringVar(&ListenRoute,"ListenRoute","/4u6385IP","Set http server listen Route") func OutIPAddress(w http.ResponseWriter, r *http.Request) slice01 := strings.Split(r.RemoteAddr,":") log.Println(time.Now(),"-- 4u6385IP --",r) fmt.Fprintf(w,slice01[0]) func main() flag.Parse() if h flag.Usage() os.Exit(0) if ! strings.HasPrefix(ListenRoute,"/") ListenRoute = "/" + ListenRoute http.HandleFunc(ListenRoute,OutIPAddress) log.Println("Server running on http://" + LitenAddr + ListenRoute) s := &http.Server Addr: LitenAddr, ReadTimeout:10*time.Second, WriteTimeout:10*time.Second, MaxHeaderBytes:1<<20, log.Fatal(s.ListenAndServe())
打包为可执行文件
# go build -o ReturnOutIP
获取帮助
# ./ReturnOutIP -h Usage of ./ReturnOutIP: -ListenAddr string Set http server listen address (default "0.0.0.0:93") -ListenRoute string Set http server listen Route (default "/4u6385IP") -h This help #
默认参数
默认运行监听的端口为: 0.0.0.0:93 监听的http路由为 /4u6385IP
# ./ReturnOutIP 2019/09/03 15:36:55 Server running on http://0.0.0.0:93/4u6385IP
指定监听的端口和路由
``` bash # ./ReturnOutIP -ListenAddr "0.0.0.0:95" -ListenRoute ‘/OutIP‘ 2019/09/03 15:41:24 Server running on http://0.0.0.0:95/OutIP ```
客户端扩展: https://www.cnblogs.com/wang-li/p/11437310.html
以上是关于Golang 服务器返回公网地址的主要内容,如果未能解决你的问题,请参考以下文章
Ftp服务器返回的PASV地址为内网IP,无法建立数据连接,求破!!!
解决golang使用elastic连接elasticsearch时自动转换连接地址
解决golang使用elastic连接elasticsearch时自动转换连接地址