golang api获取客户端地址

/*
 * @Author: lmy
 * @Date: 2023-10-30 10:24:11
 * @LastEditors: lmy
 * @LastEditTime: 2023-10-30 15:28:27
 * @FilePath: \golang代码\200_function.go
 * @Description: 正式版
 */
package main

import (
	"fmt"
	"net"
	"net/http"

	"github.com/thinkeridea/go-extend/exnet"
)

// 获取客户端IP地址
func getClientIPaddress(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	fmt.Fprint(w, RemoteIp(r))
}

// RemoteIp 返回远程客户端的 IP,如 192.168.1.1
func RemoteIp(req *http.Request) string {
	remoteAddr := req.RemoteAddr
	if ip := exnet.ClientPublicIP(req); ip != "" {
		remoteAddr = ip
	} else if ip := exnet.ClientIP(req); ip != "" {
		remoteAddr = ip
	} else if ip := req.Header.Get("X-Real-IP"); ip != "" {
		remoteAddr = ip
	} else if ip = req.Header.Get("X-Forwarded-For"); ip != "" {
		remoteAddr = ip
	} else {
		remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
	}
	if remoteAddr == "::1" {
		remoteAddr = "127.0.0.1"
	}
	return remoteAddr
}

你可能感兴趣的:(golang,开发语言,后端)