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
+17.1k Golang : convert int to string
+13.8k Golang : Set up source IP address before making HTTP request
+6.8k Golang : Set or add headers for many or different handlers
+4.1k Golang : What is StructTag and how to get StructTag's value?
+3k Javascript : Access JSON data example
+8.2k Golang : flag provided but not defined error
+33.1k Golang : Read a text file and replace certain words
+10.3k Golang : Sort and reverse sort a slice of bytes
+21.2k Golang : Print out struct values in string format
+8.2k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+8.5k Golang : ISO8601 Duration Parser example