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
+4.8k Golang : How to fix html/template : "somefile" is undefined error?
+9.4k Golang : Pagination with go-paginator configuration example
+7.4k Golang : Populate slice with sequential integers example
+21.8k Golang : Upload to S3 with official aws-sdk-go package
+16.4k Golang : Example for RSA package functions
+6.1k Golang : Scan files for certain pattern and rename part of the files
+14.7k Golang : Put UTF8 text on OpenCV video capture image frame
+13.6k Golang : invalid character ',' looking for beginning of value
+4.9k Golang : Humanize and Titleize functions
+9.1k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+15.1k Golang : Find smallest number in array
+5.3k Golang : Get Alexa ranking data example