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
+8.2k Golang : Find relative luminance or color brightness
+10.1k Golang : Find and replace data in all files recursively
+16.3k Golang :Trim white spaces from a string
+13.3k Golang : Generate Code128 barcode
+9.5k Golang : Read file with ioutil
+9.6k Golang : Quadratic example
+14.5k Golang : Missing Bazaar command
+11.6k Golang : Find age or leap age from date of birth example
+17.2k Golang : How to tell if a file is compressed either gzip or zip ?
+10.8k Golang : Removes punctuation or defined delimiter from the user's input
+7.4k Golang : Get YouTube playlist
+14.2k Golang : Get uploaded file name or access uploaded files