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.7k Javascript : How to refresh page with JQuery ?
+5.9k Mac OSX : Find large files by size
+8.6k Golang : Resumable upload to Google Drive(RESTful) example
+19.7k Curl usage examples with Golang
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+3.9k Unix/Linux : How to pipe/save output of a command to file?
+46.9k Golang : Upload file from web browser to server
+10.2k Golang : Post data with url.Values{}
+8.6k Golang : Turn string or text file into slice example
+10.5k Golang : Change date format to yyyy-mm-dd
+4.2k Golang : Pad file extension automagically
+61.4k Golang : Convert HTTP Response body to string