Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetLocalIpAddress ¶
func GetLocalIpAddress() (ipaddr []string)
GetLocalIpAddress returns all non-loopback IPv4 addresses assigned to the local machine's network interfaces.
Example ¶
ExampleGetLocalIpAddress shows how to retrieve all non-loopback IPv4 addresses assigned to the local machine — useful for logging the pod IP at startup.
package main
import (
"fmt"
"github.com/phcp-tech/common-library-golang/network"
)
func main() {
addrs := network.GetLocalIpAddress()
for _, ip := range addrs {
fmt.Println(ip)
}
}
Output:
func GetRemoteIp ¶
GetRemoteIp returns the remote client IP address from the HTTP request. It inspects the X-Forwarded-For header first (required in AWS Lambda and other reverse-proxy environments), then X-Real-IP, and finally falls back to the TCP remote address. The loopback address "::1" is normalised to "127.0.0.1". When X-Forwarded-For contains multiple addresses, the first one is returned.
Example ¶
ExampleGetRemoteIp shows how to extract the real client IP in a reverse-proxy environment where the original IP is forwarded via X-Forwarded-For.
package main
import (
"fmt"
"net/http"
"github.com/phcp-tech/common-library-golang/network"
)
func main() {
req, _ := http.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Forwarded-For", "203.0.113.5")
req.RemoteAddr = "10.0.0.1:1234"
fmt.Println(network.GetRemoteIp(req))
}
Output: 203.0.113.5
Example (MultipleProxies) ¶
ExampleGetRemoteIp_multipleProxies shows that when X-Forwarded-For contains multiple addresses (set by a chain of proxies), the first (original client) IP is returned.
package main
import (
"fmt"
"net/http"
"github.com/phcp-tech/common-library-golang/network"
)
func main() {
req, _ := http.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Forwarded-For", "203.0.113.5, 10.0.0.2, 10.0.0.3")
req.RemoteAddr = "10.0.0.1:1234"
fmt.Println(network.GetRemoteIp(req))
}
Output: 203.0.113.5
Example (XRealIP) ¶
ExampleGetRemoteIp_xRealIP shows the X-Real-IP fallback used by Nginx when X-Forwarded-For is not set.
package main
import (
"fmt"
"net/http"
"github.com/phcp-tech/common-library-golang/network"
)
func main() {
req, _ := http.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("X-Real-IP", "198.51.100.7")
req.RemoteAddr = "10.0.0.1:1234"
fmt.Println(network.GetRemoteIp(req))
}
Output: 198.51.100.7
Types ¶
This section is empty.