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
+25.7k Golang : Generate MD5 checksum of a file
+28.3k Golang : Connect to database (MySQL/MariaDB) server
+41.4k Golang : How to count duplicate items in slice/array?
+9.1k Golang : Go as a script or running go with shebang/hashbang style
+8.5k Your page has meta tags in the body instead of the head
+24.1k Golang : Call function from another package
+9.5k Golang : Launch Mac OS X Preview (or other OS) application from your program example
+7.8k Android Studio : AlertDialog to get user attention example
+24.1k Golang : Use regular expression to validate domain name
+6.1k Golang : Experimenting with the Rejang script
+9.2k Golang : How to use Gorilla webtoolkit context package properly
+6.9k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?