Golang : How do I get the local IP (non-loopback) address ?
There are times we need to know the local machine IP address to send data packets to other services/server/clients and in this tutorial will show you how to get it done. The code below will find out the local machine IP non-loopback addresses.
package main
import (
"fmt"
"net"
"os"
)
func main() {
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
fmt.Println(ipnet.IP.String())
}
}
}
}
You might be interested to read how to get client IP address tutorial as well.
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13k Golang : Verify token from Google Authenticator App
+38.9k Golang : Remove dashes(or any character) from string
+9.2k Golang : ffmpeg with os/exec.Command() returns non-zero status
+4.7k Golang : Constant and variable names in native language
+14k Golang : Parsing or breaking down URL
+22.1k Golang : Set and Get HTTP request headers example
+11.9k Golang : Forwarding a local port to a remote server example
+5.1k Golang : Intercept, inject and replay HTTP traffics from web server
+10.6k Golang : Generate random elements without repetition or duplicate
+76.9k Golang : How to return HTTP status code?
+13.3k Golang : How to determine if a year is leap year?