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
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+25.7k Mac/Linux and Golang : Fix bind: address already in use error
+7.2k Golang : How to handle file size larger than available memory panic issue
+7.9k Golang : How To Use Panic and Recover
+7.3k Golang : Shuffle strings array
+21.6k Golang : Join arrays or slices example
+18.6k Golang : How to make function callback or pass value from function as parameter?
+4.9k Golang : Issue HTTP commands to server and port example
+11.4k Golang : Calculations using complex numbers example
+5.1k Unix/Linux : How to archive and compress entire directory ?
+16.6k Golang : How to generate QR codes?
+11.4k Golang : Surveillance with web camera and OpenCV