Created
December 16, 2025 11:45
-
-
Save oddmario/31ad04bad86770486b5b8d1e3b9b63a6 to your computer and use it in GitHub Desktop.
A Go function for returning the current public IP address (supports both IPv4 and IPv6)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "github.com/pion/stun" | |
| ) | |
| func getPublicIP(ipType string) ([]string, error) { | |
| var network string = "udp4" | |
| if ipType == "ipv6" { | |
| network = "udp6" | |
| } | |
| var ips []string = []string{} | |
| // Connect to a public STUN server (Google maintains a free one) | |
| c, err := stun.Dial(network, "stun.l.google.com:19302") | |
| if err != nil { | |
| return ips, err | |
| } | |
| defer c.Close() | |
| // Create a message to "bind" (ask for our address) | |
| message := stun.MustBuild(stun.TransactionID, stun.BindingRequest) | |
| var err_ error = nil | |
| // Send the request and wait for a response | |
| if err := c.Do(message, func(res stun.Event) { | |
| if res.Error != nil { | |
| err_ = res.Error | |
| } else { | |
| // Decode the XOR-MAPPED-ADDRESS attribute | |
| var xorAddr stun.XORMappedAddress | |
| if err := xorAddr.GetFrom(res.Message); err != nil { | |
| err_ = err | |
| } else { | |
| publicIP := xorAddr.IP.String() | |
| ips = append(ips, publicIP) | |
| } | |
| } | |
| }); err != nil { | |
| return ips, err | |
| } | |
| if ipType == "both" { | |
| ipv6Query, err := getPublicIP("ipv6") | |
| if err == nil { | |
| ips = append(ips, ipv6Query[0]) | |
| } | |
| } | |
| return ips, err_ | |
| } | |
| func main() { | |
| fmt.Println(getPublicIP("")) // retrieve the IPv4 | |
| fmt.Println(getPublicIP("ipv6")) // retrieve the IPv6 | |
| fmt.Println(getPublicIP("both")) // retrieve both IP types | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment