How do I get my public IP in Go? The method req.Header.Get("X-Forwarded-For") returns an array of IP arrays. How do we identify which one is public and which one is internal? Is there any other method to fetch my public (external) IP?
5 Answers
The following IP blocks are reserved for private IP addresses.
Class Starting IPAddress Ending IP Address # of Hosts A 10.0.0.0 10.255.255.255 16,777,216 B 172.16.0.0 172.31.255.255 1,048,576 C 192.168.0.0 192.168.255.255 65,536 Link-local-u 169.254.0.0 169.254.255.255 65,536 Link-local-m 224.0.0.0 224.0.0.255 256 Local 127.0.0.0 127.255.255.255 16777216 You may write a function that checks for if the ip comes under these
Here is an attempt to do the same,the code below is not handling ipv6 please add if needed
func IsPublicIP(IP net.IP) bool { if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() { return false } if ip4 := IP.To4(); ip4 != nil { switch { case ip4[0] == 10: return false case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31: return false case ip4[0] == 192 && ip4[1] == 168: return false default: return true } } return false } Here is a Go.dev Playground demo
Comments
Using an IP api will 100% give you your public IP :
type IP struct { Query string } func getip2() string { req, err := http.Get("http://ip-api.com/json/") if err != nil { return err.Error() } defer req.Body.Close() body, err := ioutil.ReadAll(req.Body) if err != nil { return err.Error() } var ip IP json.Unmarshal(body, &ip) return ip.Query } Comments
import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) type IP struct { Query string } func main() { m := getip2() fmt.Print(m) } func getip2() string { req, err := http.Get("http://ip-api.com/json/") if err != nil { return err.Error() } defer req.Body.Close() body, err := ioutil.ReadAll(req.Body) if err != nil { return err.Error() } var ip IP json.Unmarshal(body, &ip) // fmt.Print(ip.Query) return ip.Query } 1 Comment
Hymns For Disco
Instead of copying the other answer, it's better if you suggest an edit.
package main import ( "fmt" "net/http" "io/ioutil" ) func main() { resp, _ := http.Get("https://api.ipquery.io/?format=json") body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) } From the IPQuery Docs
1 Comment
TylerH
This is your second time in a couple of weeks recommending this website, "ipquery.io". Are you affiliated with this website?
I use the following code for finding out public IP :
//function to get the public ip address func GetOutboundIP() string { conn, err := net.Dial("udp", "8.8.8.8:80") HandleError("net.Dial: ",err) defer conn.Close() localAddr := conn.LocalAddr().String() idx := strings.LastIndex(localAddr, ":") return localAddr[0:idx] } 2 Comments
Dowland Aiello
Unfortunately, this will only work on networks that don't employ the use of NAT. Please revise your answer.
VikasPushkar
this may return an private ip as well in case when your machine is behind the NAT