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
+5.3k Golang : Calculate half life decay example
+12.4k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+6.9k Golang : Find the longest line of text example
+10.9k PHP : Convert(cast) bigInt to string
+16.8k Golang : Get own process identifier
+7.4k Golang : How to convert strange string to JSON with json.MarshalIndent
+20.8k Golang : Saving private and public key to files
+9.4k Golang : How to protect your source code from client, hosting company or hacker?
+6k AWS S3 : Prevent Hotlinking policy
+21.4k Golang : Clean up null characters from input data
+19.7k Golang : Set or Add HTTP Request Headers
+22.8k Golang : Round float to precision example