Skip to content

Instantly share code, notes, and snippets.

@checkaayush
Last active November 25, 2018 12:06
Show Gist options
  • Save checkaayush/36a531e7a2e2268b7c9c32a266c51b77 to your computer and use it in GitHub Desktop.
Save checkaayush/36a531e7a2e2268b7c9c32a266c51b77 to your computer and use it in GitHub Desktop.
Get your public and private IP addresses with one command
// Utility to get your public and private IP addresses
// Usage:
// 1. Run: go build -o myip myip.go
// 2. Add the executable myip to your PATH
// 3. Run: myip
package main
import (
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
)
// GetPublicIP returns your public IP address
func GetPublicIP() string {
resp, err := http.Get("https://api.ipify.org")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
ip := string(body)
return ip
}
// GetPrivateIP returns your preferred outbound private IP address
func GetPrivateIP() string {
conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
localAddr := conn.LocalAddr().(*net.UDPAddr)
ip := localAddr.IP.String()
return ip
}
func main() {
fmt.Printf("Public IP: %s\nPrivate IP: %s\n", GetPublicIP(), GetPrivateIP())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment