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.1k Golang : Pad file extension automagically
+24.2k Golang : GORM read from database example
+16.8k Golang : Get number of CPU cores
+23.7k Golang : Call function from another package
+20.2k Golang : Pipe output from one os.Exec(shell command) to another command
+27.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+14.3k Golang : Execute function at intervals or after some delay
+14k Golang : How to pass map to html template and access the map's elements
+15.1k Golang : invalid character ',' looking for beginning of value
+9.2k Golang : Get all countries currencies code in JSON format
+10k Golang : Embed secret text string into binary(executable) file
+14k Golang : Convert IP version 6 address to integer or decimal number