How to get Local IP Address in Golang with example
- Admin
- Mar 10, 2024
- Golang-examples
Typically, when you retrieve the IP address using Golang APIs, it provides a loopback address (127.0.0.1) configured in the /etc/hosts
file, and it does not give the local public outbound IP address, such as 162.221.xxx.xxx.
This tutorial explains how to obtain a local IP address in Golang.
How to get the Current Local outbound IP address in Golang
- Wrote a Golang function that returns a
net.IP
object. - Created a connection by specifying a Google DNS server (8.8.8.8:80) using a
UDP
connection instead ofTCP
. - The reason for using a UDP connection is that it doesn’t establish a connection to the target, and it avoids the need for a handshake or connection.
- The connect object’s getAddress method returns the IP address of the subnet.
- We can also obtain the IP address 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)
}
Conclusion
Obtaining a local IP address is straightforward with the net package. You can print the locally bound IP address easily using this package.