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
+12.8k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+12.7k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter
+12.9k Golang : zlib compress file example
+10.8k Golang : Allow Cross-Origin Resource Sharing request
+19.1k Golang : Padding data for encryption and un-padding data for decryption
+30.7k Golang : Generate random string
+7.7k Golang : Rot13 and Rot5 algorithms example
+9.1k Golang : GMail API create and send draft with simple upload attachment example
+24.2k Golang : Use regular expression to validate domain name
+11.2k Golang : Generate random elements without repetition or duplicate
+18.6k Golang : How to remove certain lines from a file