How to get Local IP Address in Golang with example
- Admin
- Aug 17, 2023
- Golang-examples
This tutorial explains how to get a local IP address in Golang.
Usually, When you retrieved the IP address using golang API’s, gives a loopback address 12.0.0.1 configured in the/etc/hosts
file, and does not give a local public outbound IP address such as 132.121.xxx.xxx.
How to get the Current Local outbound IP address in Golang
- Written golang function that returns net.IP object
- Created a connection by providing a GOOGle DNS server(8.8.8.8:80”) using a UDP connection instead of TCP.
- The reason to use a UDP connection is, It does not connect to the target and does not apply handshake or connection
- connect object getAddress method returns the IP address of the subnet IP address.
- We can also get the ipaddress in CIDR notation
Here is an example
package main
import (
"fmt"
"log"
"net"
)
// Local address of the running system
func getLocalAddress() net.IP {
con, error := net.Dial("udp", "8.8.8.8:80")
if error != nil {
log.Fatal(error )
}
defer con.Close()
localAddress := con.LocalAddr().(*net.UDPAddr)
return localAddress.IP
}
func main() {
ipString := GetOutboundIP()
fmt.Println(ipString)
}