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
+24.5k Golang : Change file read or write permission example
+5k Python : Convert(cast) bytes to string example
+11k Golang : Replace a parameter's value inside a configuration file example
+7.4k Golang : Convert source code to assembly language
+5.6k Python : Print unicode escape characters and string
+19.6k Golang : Example for DSA(Digital Signature Algorithm) package functions
+5.1k Swift : Convert (cast) Float to Int or Int32 value
+12k Golang : Convert decimal number(integer) to IPv4 address
+26.9k Golang : Find files by extension
+12.2k Golang : calculate elapsed run time
+8.5k Golang : Ackermann function example
+4.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example