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.2k Javascript : Generate random key with specific length
+4.3k Golang : How to deal with configuration data?
+26.8k Golang : Read, Write(Create) and Delete Cookie example
+11k Android Studio : Highlight ImageButton when pressed on example
+12.9k Golang : Check if a file exist or not
+5.2k Golang : How to get capacity of a slice or array?
+9.8k Golang : Generate random elements without repetition or duplicate
+37.8k Golang : How to iterate over a []string(array)
+4.9k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?
+8.2k Golang : How to get garbage collection data?
+8.4k Golang : Accessing content anonymously with Tor
+6.5k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image