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
+1.5k Golang : Scan forex opportunities by Bollinger bands
+3.8k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+3.7k Golang : How to join strings?
+3.8k Golang : Concatenate (combine) buffer data example
+15k Golang : Get file last modified date and time
+8k Golang : Tutorial on loading GOB and PEM files
+6.3k Golang : How to detect a server/machine network interface capabilities?
+9.5k Golang : Check if a file exist or not
+15.5k Golang : Get current file path of a file or executable
+13.1k Golang : Sort and reverse sort a slice of strings
+3.7k Golang : Reverse a string with unicode
+4.2k Golang : Check if user agent is a robot or crawler example